diff options
Diffstat (limited to 'test')
112 files changed, 3323 insertions, 3328 deletions
diff --git a/test/aaa_profiling/test_compiler.py b/test/aaa_profiling/test_compiler.py index a5d5d973b..18d0118f1 100644 --- a/test/aaa_profiling/test_compiler.py +++ b/test/aaa_profiling/test_compiler.py @@ -5,7 +5,7 @@ from sqlalchemy.engine import default class CompileTest(TestBase, AssertsExecutionResults): @classmethod def setup_class(cls): - + global t1, t2, metadata metadata = MetaData() t1 = Table('t1', metadata, @@ -29,9 +29,9 @@ class CompileTest(TestBase, AssertsExecutionResults): from sqlalchemy import types for t in types._type_map.values(): t._type_affinity - + cls.dialect = default.DefaultDialect() - + @profiling.function_call_count(versions={'2.7':58, '2.6':58, '3':64}) def test_insert(self): diff --git a/test/aaa_profiling/test_memusage.py b/test/aaa_profiling/test_memusage.py index 7f7cbcfb1..3e225ad08 100644 --- a/test/aaa_profiling/test_memusage.py +++ b/test/aaa_profiling/test_memusage.py @@ -32,7 +32,7 @@ class B(_base.ComparableEntity): def profile_memory(func): # run the test 50 times. if length of gc.get_objects() # keeps growing, assert false - + def profile(*args): gc_collect() samples = [0 for x in range(0, 50)] @@ -40,11 +40,11 @@ def profile_memory(func): func(*args) gc_collect() samples[x] = len(gc.get_objects()) - + print "sample gc sizes:", samples assert len(_sessions) == 0 - + for x in samples[-4:]: if x != samples[-5]: flatline = False @@ -53,7 +53,7 @@ def profile_memory(func): flatline = True # object count is bigger than when it started - if not flatline and samples[-1] > samples[0]: + if not flatline and samples[-1] > samples[0]: for x in samples[1:-2]: # see if a spike bigger than the endpoint exists if x > samples[-1]: @@ -74,19 +74,19 @@ class EnsureZeroed(_base.ORMTest): _mapper_registry.clear() class MemUsageTest(EnsureZeroed): - + # ensure a pure growing test trips the assertion @testing.fails_if(lambda: True) def test_fixture(self): class Foo(object): pass - + x = [] @profile_memory def go(): x[-1:] = [Foo(), Foo(), Foo(), Foo(), Foo(), Foo()] go() - + def test_session(self): metadata = MetaData(testing.db) @@ -179,7 +179,7 @@ class MemUsageTest(EnsureZeroed): 'pool_logging_name':'BAR'} ) sess = create_session(bind=engine) - + a1 = A(col2="a1") a2 = A(col2="a2") a3 = A(col2="a3") @@ -210,14 +210,14 @@ class MemUsageTest(EnsureZeroed): metadata.drop_all() del m1, m2, m3 assert_no_mappers() - + def test_ad_hoc_types(self): """test storage of bind processors, result processors in dialect-wide registry.""" - + from sqlalchemy.dialects import mysql, postgresql, sqlite from sqlalchemy import types - + eng = engines.testing_engine() for args in ( (types.Integer, ), @@ -236,24 +236,24 @@ class MemUsageTest(EnsureZeroed): bp = type_._cached_bind_processor(eng.dialect) rp = type_._cached_result_processor(eng.dialect, 0) go() - + assert not eng.dialect._type_memos - - + + def test_many_updates(self): metadata = MetaData(testing.db) - + wide_table = Table('t', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), *[Column('col%d' % i, Integer) for i in range(10)] ) - + class Wide(object): pass - + mapper(Wide, wide_table, _compiled_cache_size=10) - + metadata.create_all() session = create_session() w1 = Wide() @@ -262,7 +262,7 @@ class MemUsageTest(EnsureZeroed): session.close() del session counter = [1] - + @profile_memory def go(): session = create_session() @@ -279,12 +279,12 @@ class MemUsageTest(EnsureZeroed): session.flush() session.close() counter[0] += 1 - + try: go() finally: metadata.drop_all() - + @testing.fails_if(lambda : testing.db.dialect.name == 'sqlite' \ and testing.db.dialect.dbapi.version_info >= (2, 5), @@ -313,7 +313,7 @@ class MemUsageTest(EnsureZeroed): go() finally: metadata.drop_all() - + def test_mapper_reset(self): metadata = MetaData(testing.db) @@ -491,7 +491,7 @@ class MemUsageTest(EnsureZeroed): # dont need to clear_mappers() del B del A - + metadata.create_all() try: go() @@ -538,8 +538,8 @@ class MemUsageTest(EnsureZeroed): go() finally: metadata.drop_all() - - + + def test_mutable_identity(self): metadata = MetaData(testing.db) @@ -548,16 +548,16 @@ class MemUsageTest(EnsureZeroed): test_needs_autoincrement=True), Column('col2', PickleType(comparator=operator.eq, mutable=True)) ) - + class Foo(object): def __init__(self, col2): self.col2 = col2 - + mapper(Foo, table1) metadata.create_all() - + session = sessionmaker()() - + def go(): obj = [ Foo({'a':1}), @@ -573,17 +573,17 @@ class MemUsageTest(EnsureZeroed): Foo({'k':1}), Foo({'l':1}), ] - + session.add_all(obj) session.commit() - + testing.eq_(len(session.identity_map._mutable_attrs), 12) testing.eq_(len(session.identity_map), 12) obj = None gc_collect() testing.eq_(len(session.identity_map._mutable_attrs), 0) testing.eq_(len(session.identity_map), 0) - + try: go() finally: diff --git a/test/aaa_profiling/test_orm.py b/test/aaa_profiling/test_orm.py index 84a9fd025..7c89d22fd 100644 --- a/test/aaa_profiling/test_orm.py +++ b/test/aaa_profiling/test_orm.py @@ -96,21 +96,21 @@ class MergeTest(_base.MappedTest): class LoadManyToOneFromIdentityTest(_base.MappedTest): """test overhead associated with many-to-one fetches. - + Prior to the refactor of LoadLazyAttribute and query._get(), the load from identity map took 2x as many calls (65K calls here instead of around 33K) to load 1000 related objects from the identity map. - + """ - + # only need to test for unexpected variance in a large call # count here, # so remove some platforms that have wildly divergent # callcounts. __requires__ = 'python25', __unsupported_on__ = 'postgresql+pg8000', - + @classmethod def define_tables(cls, metadata): parent = Table('parent', metadata, @@ -118,7 +118,7 @@ class LoadManyToOneFromIdentityTest(_base.MappedTest): Column('data', String(20)), Column('child_id', Integer, ForeignKey('child.id')) ) - + child = Table('child', metadata, Column('id', Integer,primary_key=True), Column('data', String(20)) @@ -154,13 +154,13 @@ class LoadManyToOneFromIdentityTest(_base.MappedTest): } for i in xrange(1, 1000) ]) - + @testing.resolve_artifact_names def test_many_to_one_load_no_identity(self): sess = Session() parents = sess.query(Parent).all() - - + + @profiling.function_call_count(108019, variance=.2) def go(): for p in parents: @@ -172,11 +172,11 @@ class LoadManyToOneFromIdentityTest(_base.MappedTest): sess = Session() parents = sess.query(Parent).all() children = sess.query(Child).all() - + @profiling.function_call_count(17987, {'3':18987}) def go(): for p in parents: p.child go() - - + + diff --git a/test/aaa_profiling/test_pool.py b/test/aaa_profiling/test_pool.py index a3c0f725e..d0486fa0b 100644 --- a/test/aaa_profiling/test_pool.py +++ b/test/aaa_profiling/test_pool.py @@ -7,7 +7,7 @@ class QueuePoolTest(TestBase, AssertsExecutionResults): class Connection(object): def rollback(self): pass - + def close(self): pass diff --git a/test/aaa_profiling/test_resultset.py b/test/aaa_profiling/test_resultset.py index 51199eb3a..a0b16cb52 100644 --- a/test/aaa_profiling/test_resultset.py +++ b/test/aaa_profiling/test_resultset.py @@ -25,11 +25,11 @@ class ResultSetTest(TestBase, AssertsExecutionResults): t2.insert().execute([dict(('field%d' % fnum, u'value%d' % fnum) for fnum in range(NUM_FIELDS)) for r_num in range(NUM_RECORDS)]) - + # warm up type caches t.select().execute().fetchall() t2.select().execute().fetchall() - + def teardown(self): metadata.drop_all() @@ -54,14 +54,14 @@ class ResultSetTest(TestBase, AssertsExecutionResults): class ExecutionTest(TestBase): __only_on__ = 'sqlite' - + def test_minimal_connection_execute(self): # create an engine without any instrumentation. e = create_engine('sqlite://') c = e.connect() # ensure initial connect activities complete c.execute("select 1") - + @profiling.function_call_count(versions={'2.7':36, '2.6':35, '2.5':35, '2.4':21, '3':34}, variance=.10) diff --git a/test/aaa_profiling/test_zoomark.py b/test/aaa_profiling/test_zoomark.py index 8c1cb1c60..648efed43 100644 --- a/test/aaa_profiling/test_zoomark.py +++ b/test/aaa_profiling/test_zoomark.py @@ -16,14 +16,14 @@ metadata = None class ZooMarkTest(TestBase): """Runs the ZooMark and squawks if method counts vary from the norm. - + Each test has an associated `call_range`, the total number of accepted function calls made during the test. The count can vary between Python 2.4 and 2.5. - + Unlike a unit test, this is a ordered collection of steps. Running components individually will fail. - + """ __only_on__ = 'postgresql+psycopg2' diff --git a/test/aaa_profiling/test_zoomark_orm.py b/test/aaa_profiling/test_zoomark_orm.py index 0ea1bbd25..ce2cfdc8e 100644 --- a/test/aaa_profiling/test_zoomark_orm.py +++ b/test/aaa_profiling/test_zoomark_orm.py @@ -17,14 +17,14 @@ metadata = None class ZooMarkTest(TestBase): """Runs the ZooMark and squawks if method counts vary from the norm. - + Each test has an associated `call_range`, the total number of accepted function calls made during the test. The count can vary between Python 2.4 and 2.5. - + Unlike a unit test, this is a ordered collection of steps. Running components individually will fail. - + """ __only_on__ = 'postgresql+psycopg2' @@ -94,7 +94,7 @@ class ZooMarkTest(TestBase): Admission=4.95) session.add(wap) sdz = Zoo(Name=u'San Diego Zoo', Founded=datetime.date(1835, 9, - 13), Opens=datetime.time(9, 0, 0), Admission=0) + 13), Opens=datetime.time(9, 0, 0), Admission=0) session.add(sdz) bio = Zoo(Name=u'Montr\xe9al Biod\xf4me', Founded=datetime.date(1992, 6, 19), diff --git a/test/base/test_events.py b/test/base/test_events.py index e64ec3b81..e894a1f74 100644 --- a/test/base/test_events.py +++ b/test/base/test_events.py @@ -5,39 +5,39 @@ from sqlalchemy import event, exc, util class TestEvents(TestBase): """Test class- and instance-level event registration.""" - + def setUp(self): global Target - + assert 'event_one' not in event._registrars assert 'event_two' not in event._registrars - + class TargetEvents(event.Events): def event_one(self, x, y): pass - + def event_two(self, x): pass - + class Target(object): dispatch = event.dispatcher(TargetEvents) - + def tearDown(self): event._remove_dispatcher(Target.__dict__['dispatch'].events) - + def test_register_class(self): def listen(x, y): pass - + event.listen(Target, "event_one", listen) - + eq_(len(Target().dispatch.event_one), 1) eq_(len(Target().dispatch.event_two), 0) def test_register_instance(self): def listen(x, y): pass - + t1 = Target() event.listen(t1, "event_one", listen) @@ -45,7 +45,7 @@ class TestEvents(TestBase): eq_(len(t1.dispatch.event_one), 1) eq_(len(Target().dispatch.event_two), 0) eq_(len(t1.dispatch.event_two), 0) - + def test_register_class_instance(self): def listen_one(x, y): pass @@ -54,7 +54,7 @@ class TestEvents(TestBase): pass event.listen(Target, "event_one", listen_one) - + t1 = Target() event.listen(t1, "event_one", listen_two) @@ -62,20 +62,20 @@ class TestEvents(TestBase): eq_(len(t1.dispatch.event_one), 2) eq_(len(Target().dispatch.event_two), 0) eq_(len(t1.dispatch.event_two), 0) - + def listen_three(x, y): pass - + event.listen(Target, "event_one", listen_three) eq_(len(Target().dispatch.event_one), 2) eq_(len(t1.dispatch.event_one), 3) - + class TestAcceptTargets(TestBase): """Test default target acceptance.""" - + def setUp(self): global TargetOne, TargetTwo - + class TargetEventsOne(event.Events): def event_one(self, x, y): pass @@ -83,37 +83,37 @@ class TestAcceptTargets(TestBase): class TargetEventsTwo(event.Events): def event_one(self, x, y): pass - + class TargetOne(object): dispatch = event.dispatcher(TargetEventsOne) class TargetTwo(object): dispatch = event.dispatcher(TargetEventsTwo) - + def tearDown(self): event._remove_dispatcher(TargetOne.__dict__['dispatch'].events) event._remove_dispatcher(TargetTwo.__dict__['dispatch'].events) - + def test_target_accept(self): """Test that events of the same name are routed to the correct collection based on the type of target given. - + """ def listen_one(x, y): pass def listen_two(x, y): pass - + def listen_three(x, y): pass def listen_four(x, y): pass - + event.listen(TargetOne, "event_one", listen_one) event.listen(TargetTwo, "event_one", listen_two) - + eq_( list(TargetOne().dispatch.event_one), [listen_one] @@ -129,7 +129,7 @@ class TestAcceptTargets(TestBase): event.listen(t1, "event_one", listen_three) event.listen(t2, "event_one", listen_four) - + eq_( list(t1.dispatch.event_one), [listen_one, listen_three] @@ -139,13 +139,13 @@ class TestAcceptTargets(TestBase): list(t2.dispatch.event_one), [listen_two, listen_four] ) - + class TestCustomTargets(TestBase): """Test custom target acceptance.""" def setUp(self): global Target - + class TargetEvents(event.Events): @classmethod def _accept_with(cls, target): @@ -153,7 +153,7 @@ class TestCustomTargets(TestBase): return Target else: return None - + def event_one(self, x, y): pass @@ -162,30 +162,30 @@ class TestCustomTargets(TestBase): def tearDown(self): event._remove_dispatcher(Target.__dict__['dispatch'].events) - + def test_indirect(self): def listen(x, y): pass - + event.listen("one", "event_one", listen) eq_( list(Target().dispatch.event_one), [listen] ) - + assert_raises( exc.InvalidRequestError, event.listen, listen, "event_one", Target ) - + class TestListenOverride(TestBase): """Test custom listen functions which change the listener function signature.""" - + def setUp(self): global Target - + class TargetEvents(event.Events): @classmethod def _listen(cls, target, identifier, fn, add=False): @@ -194,9 +194,9 @@ class TestListenOverride(TestBase): fn(x + y) else: adapt = fn - + event.Events._listen(target, identifier, adapt) - + def event_one(self, x, y): pass @@ -205,43 +205,43 @@ class TestListenOverride(TestBase): def tearDown(self): event._remove_dispatcher(Target.__dict__['dispatch'].events) - + def test_listen_override(self): result = [] def listen_one(x): result.append(x) - + def listen_two(x, y): result.append((x, y)) - + event.listen(Target, "event_one", listen_one, add=True) event.listen(Target, "event_one", listen_two) t1 = Target() t1.dispatch.event_one(5, 7) t1.dispatch.event_one(10, 5) - + eq_(result, [ 12, (5, 7), 15, (10, 5) ] ) - + class TestPropagate(TestBase): def setUp(self): global Target - + class TargetEvents(event.Events): def event_one(self, arg): pass - + def event_two(self, arg): pass - + class Target(object): dispatch = event.dispatcher(TargetEvents) - - + + def test_propagate(self): result = [] def listen_one(target, arg): @@ -249,16 +249,16 @@ class TestPropagate(TestBase): def listen_two(target, arg): result.append((target, arg)) - + t1 = Target() - + event.listen(t1, "event_one", listen_one, propagate=True) event.listen(t1, "event_two", listen_two) t2 = Target() - + t2.dispatch._update(t1.dispatch) - + t2.dispatch.event_one(t2, 1) t2.dispatch.event_two(t2, 2) eq_(result, [(t2, 1)]) diff --git a/test/base/test_utils.py b/test/base/test_utils.py index d11644dbe..845114447 100644 --- a/test/base/test_utils.py +++ b/test/base/test_utils.py @@ -85,7 +85,7 @@ class FrozenDictTest(TestBase): d = util.frozendict({1:2, 3:4}) for loads, dumps in picklers(): print loads(dumps(d)) - + class MemoizedAttrTest(TestBase): def test_memoized_property(self): @@ -96,7 +96,7 @@ class MemoizedAttrTest(TestBase): v = val[0] val[0] += 1 return v - + ne_(Foo.bar, None) f1 = Foo() assert 'bar' not in f1.__dict__ @@ -120,7 +120,7 @@ class MemoizedAttrTest(TestBase): eq_(f1.bar(), 20) eq_(f1.bar(), 20) eq_(val[0], 21) - + class ColumnCollectionTest(TestBase): def test_in(self): cc = sql.ColumnCollection() @@ -151,7 +151,7 @@ class ColumnCollectionTest(TestBase): class LRUTest(TestBase): - def test_lru(self): + def test_lru(self): class item(object): def __init__(self, id): self.id = id @@ -191,7 +191,7 @@ class LRUTest(TestBase): l[25] = i2 assert 25 in l assert l[25] is i2 - + class ImmutableSubclass(str): pass @@ -205,7 +205,7 @@ class FlattenIteratorTest(TestBase): def test_str_with_iter(self): """ensure that a str object with an __iter__ method (like in PyPy) is not interpreted as an iterable. - + """ class IterString(str): def __iter__(self): @@ -214,7 +214,7 @@ class FlattenIteratorTest(TestBase): assert list(util.flatten_iterator([IterString('asdf'), [IterString('x'), IterString('y')]])) == ['asdf', 'x', 'y'] - + class HashOverride(object): def __init__(self, value=None): self.value = value @@ -235,7 +235,7 @@ class EqOverride(object): return self.value != other.value else: return True - + class HashEqOverride(object): def __init__(self, value=None): self.value = value @@ -371,7 +371,7 @@ class IdentitySetTest(TestBase): assert_raises(TypeError, lambda: s1 - [3, 4, 5]) class OrderedIdentitySetTest(TestBase): - + def assert_eq(self, identityset, expected_iterable): expected = [id(o) for o in expected_iterable] found = [id(o) for o in identityset] @@ -386,10 +386,10 @@ class OrderedIdentitySetTest(TestBase): def test_intersection(self): elem = object eq_ = self.assert_eq - + a, b, c, d, e, f, g = \ elem(), elem(), elem(), elem(), elem(), elem(), elem() - + s1 = util.OrderedIdentitySet([a, b, c]) s2 = util.OrderedIdentitySet([d, e, f]) s3 = util.OrderedIdentitySet([a, d, f, g]) @@ -426,7 +426,7 @@ class DictlikeIteritemsTest(TestBase): d = UserDict.UserDict(a=1,b=2,c=3) self._ok(d) # end Py2K - + def test_object(self): self._notok(object()) @@ -486,7 +486,7 @@ class DuckTypeCollectionTest(TestBase): class ForcedSet(list): __emulates__ = set - + for type_ in (set, # Py2K sets.Set, @@ -1043,7 +1043,7 @@ class TestClassHierarchy(TestBase): eq_(set(util.class_hierarchy(A)), set((A, B, C, object))) eq_(set(util.class_hierarchy(B)), set((A, B, C, object))) - + # Py2K def test_oldstyle_mixin(self): class A(object): @@ -1059,7 +1059,7 @@ class TestClassHierarchy(TestBase): eq_(set(util.class_hierarchy(Mixin)), set()) eq_(set(util.class_hierarchy(A)), set((A, B, object))) # end Py2K - + class TestClassProperty(TestBase): diff --git a/test/bootstrap/noseplugin.py b/test/bootstrap/noseplugin.py index 5ffa8b89f..0303c84db 100644 --- a/test/bootstrap/noseplugin.py +++ b/test/bootstrap/noseplugin.py @@ -26,7 +26,7 @@ class NoseSQLAlchemy(Plugin): Handles the setup and extra properties required for testing SQLAlchemy """ enabled = True - + # nose 1.0 will allow us to replace the old "sqlalchemy" plugin, # if installed, using the same name, but nose 1.0 isn't released yet... name = '_sqlalchemy' @@ -79,33 +79,33 @@ class NoseSQLAlchemy(Plugin): file_config.readfp(StringIO.StringIO(base_config)) file_config.read(['test.cfg', os.path.expanduser('~/.satest.cfg')]) config.file_config = file_config - + def configure(self, options, conf): Plugin.configure(self, options, conf) self.options = options for fn in pre_configure: fn(self.options, file_config) - + def begin(self): global testing, requires, util from test.lib import testing, requires from sqlalchemy import util - + testing.db = db testing.requires = requires # Lazy setup of other options (post coverage) for fn in post_configure: fn(self.options, file_config) - + def describeTest(self, test): return "" - + def wantFunction(self, fn): if fn.__module__.startswith('test.lib') or \ fn.__module__.startswith('test.bootstrap'): return False - + def wantClass(self, cls): """Return true if you want the main test selector to collect tests from this class, false if you don't, and None if you don't @@ -124,7 +124,7 @@ class NoseSQLAlchemy(Plugin): return True else: return not self.__should_skip_for(cls) - + def __should_skip_for(self, cls): if hasattr(cls, '__requires__'): def test_suite(): return 'ok' @@ -141,13 +141,13 @@ class NoseSQLAlchemy(Plugin): print "'%s' unsupported on DB implementation '%s'" % ( cls.__class__.__name__, testing.db.name) return True - + if getattr(cls, '__only_on__', None): spec = testing.db_spec(*util.to_list(cls.__only_on__)) if not spec(testing.db): print "'%s' unsupported on DB implementation '%s'" % ( cls.__class__.__name__, testing.db.name) - return True + return True if getattr(cls, '__skip_if__', False): for c in getattr(cls, '__skip_if__'): @@ -155,7 +155,7 @@ class NoseSQLAlchemy(Plugin): print "'%s' skipped by %s" % ( cls.__class__.__name__, c.__name__) return True - + for rule in getattr(cls, '__excluded_on__', ()): if testing._is_excluded(*rule): print "'%s' unsupported on DB %s version %s" % ( @@ -169,10 +169,10 @@ class NoseSQLAlchemy(Plugin): def afterTest(self, test): testing.resetwarnings() - + def afterContext(self): testing.global_cleanup_assertions() - + #def handleError(self, test, err): #pass diff --git a/test/dialect/test_firebird.py b/test/dialect/test_firebird.py index 814c267b5..ce708936b 100644 --- a/test/dialect/test_firebird.py +++ b/test/dialect/test_firebird.py @@ -169,7 +169,7 @@ CREATE DOMAIN DOM_ID INTEGER NOT NULL CREATE TABLE A ( ID DOM_ID /* INTEGER NOT NULL */ DEFAULT 0 ) """ - + # the 'default' keyword is lower case here TABLE_B = """\ CREATE TABLE B ( @@ -222,14 +222,14 @@ ID DOM_ID /* INTEGER NOT NULL */ default 0 ) table_a = Table('a', metadata, autoload=True) eq_(table_a.c.id.server_default.arg.text, "0") - + def test_lowercase_default_name(self): metadata = MetaData(testing.db) table_b = Table('b', metadata, autoload=True) eq_(table_b.c.id.server_default.arg.text, "0") - + class CompileTest(TestBase, AssertsCompiledSQL): diff --git a/test/dialect/test_mssql.py b/test/dialect/test_mssql.py index 68203cfea..6cc327151 100644 --- a/test/dialect/test_mssql.py +++ b/test/dialect/test_mssql.py @@ -31,15 +31,15 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'UPDATE sometable SET somecolumn=:somecolum' 'n WHERE sometable.somecolumn = ' ':somecolumn_1', dict(somecolumn=10)) - + # TODO: should this be for *all* MS-SQL dialects ? def test_mxodbc_binds(self): """mxodbc uses MS-SQL native binds, which aren't allowed in various places.""" - + mxodbc_dialect = mxodbc.dialect() t = table('sometable', column('foo')) - + for expr, compile in [ ( select([literal("x"), literal("y")]), @@ -61,7 +61,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): ) ]: self.assert_compile(expr, compile, dialect=mxodbc_dialect) - + def test_in_with_subqueries(self): """Test that when using subqueries in a binary expression the == and != are changed to IN and NOT IN respectively. @@ -151,7 +151,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'remotetable_1.value FROM mytable JOIN ' 'remote_owner.remotetable AS remotetable_1 ' 'ON remotetable_1.rem_id = mytable.myid') - + self.assert_compile(select([table4.c.rem_id, table4.c.value]).apply_labels().union(select([table1.c.myid, table1.c.description]).apply_labels()).alias().select(), @@ -163,8 +163,8 @@ class CompileTest(TestBase, AssertsCompiledSQL): "SELECT mytable.myid AS mytable_myid, mytable.description " "AS mytable_description FROM mytable) AS anon_1" ) - - + + def test_delete_schema(self): metadata = MetaData() tbl = Table('test', metadata, Column('id', Integer, @@ -337,9 +337,9 @@ class CompileTest(TestBase, AssertsCompiledSQL): def test_limit_using_top(self): t = table('t', column('x', Integer), column('y', Integer)) - + s = select([t]).where(t.c.x==5).order_by(t.c.y).limit(10) - + self.assert_compile( s, "SELECT TOP 10 t.x, t.y FROM t WHERE t.x = :x_1 ORDER BY t.y", @@ -348,9 +348,9 @@ class CompileTest(TestBase, AssertsCompiledSQL): def test_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer)) - + s = select([t]).where(t.c.x==5).order_by(t.c.y).offset(20) - + self.assert_compile( s, "SELECT anon_1.x, anon_1.y FROM (SELECT t.x AS x, t.y " @@ -362,9 +362,9 @@ class CompileTest(TestBase, AssertsCompiledSQL): def test_limit_offset_using_window(self): t = table('t', column('x', Integer), column('y', Integer)) - + s = select([t]).where(t.c.x==5).order_by(t.c.y).limit(10).offset(20) - + self.assert_compile( s, "SELECT anon_1.x, anon_1.y " @@ -375,9 +375,9 @@ class CompileTest(TestBase, AssertsCompiledSQL): "WHERE mssql_rn > :mssql_rn_1 AND mssql_rn <= :mssql_rn_2", {u'mssql_rn_1': 20, u'mssql_rn_2': 30, u'x_1': 5} ) - - - + + + class IdentityInsertTest(TestBase, AssertsCompiledSQL): __only_on__ = 'mssql' __dialect__ = mssql.MSDialect() @@ -496,7 +496,7 @@ class ReflectionTest(TestBase, ComparesTables): and table2.c['col1'].default assert sequence.start == 2 assert sequence.increment == 3 - + @testing.emits_warning("Did not recognize") @testing.provide_metadata def test_skip_types(self): @@ -509,14 +509,14 @@ class ReflectionTest(TestBase, ComparesTables): @testing.provide_metadata def test_indexes_cols(self): - + t1 = Table('t', metadata, Column('x', Integer), Column('y', Integer)) Index('foo', t1.c.x, t1.c.y) metadata.create_all() - + m2 = MetaData() t2 = Table('t', m2, autoload=True, autoload_with=testing.db) - + eq_( set(list(t2.indexes)[0].columns), set([t2.c['x'], t2.c.y]) @@ -524,38 +524,38 @@ class ReflectionTest(TestBase, ComparesTables): @testing.provide_metadata def test_indexes_cols_with_commas(self): - + t1 = Table('t', metadata, Column('x, col', Integer, key='x'), Column('y', Integer) ) Index('foo', t1.c.x, t1.c.y) metadata.create_all() - + m2 = MetaData() t2 = Table('t', m2, autoload=True, autoload_with=testing.db) - + eq_( set(list(t2.indexes)[0].columns), set([t2.c['x, col'], t2.c.y]) ) - + @testing.provide_metadata def test_indexes_cols_with_spaces(self): - + t1 = Table('t', metadata, Column('x col', Integer, key='x'), Column('y', Integer)) Index('foo', t1.c.x, t1.c.y) metadata.create_all() - + m2 = MetaData() t2 = Table('t', m2, autoload=True, autoload_with=testing.db) - + eq_( set(list(t2.indexes)[0].columns), set([t2.c['x col'], t2.c.y]) ) - + class QueryUnicodeTest(TestBase): __only_on__ = 'mssql' @@ -587,24 +587,24 @@ class QueryTest(TestBase): def test_fetchid_trigger(self): """ Verify identity return value on inserting to a trigger table. - + MSSQL's OUTPUT INSERTED clause does not work for the case of a table having an identity (autoincrement) primary key column, and which also has a trigger configured to fire upon each insert and subsequently perform an insert into a different table. - + SQLALchemy's MSSQL dialect by default will attempt to use an OUTPUT_INSERTED clause, which in this case will raise the following error: - + ProgrammingError: (ProgrammingError) ('42000', 334, "[Microsoft][SQL Server Native Client 10.0][SQL Server]The target table 't1' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.", 7748) 'INSERT INTO t1 (descr) OUTPUT inserted.id VALUES (?)' ('hello',) - + This test verifies a workaround, which is to rely on the older SCOPE_IDENTITY() call, which still works for this scenario. To enable the workaround, the Table must be instantiated @@ -759,10 +759,10 @@ class SchemaTest(TestBase): dialect = mssql.dialect() self.ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t)) - + def _column_spec(self): return self.ddl_compiler.get_column_specification(self.column) - + def test_that_mssql_default_nullability_emits_null(self): eq_("test_column VARCHAR(max) NULL", self._column_spec()) @@ -998,7 +998,7 @@ class ParseConnectTest(TestBase, AssertsCompiledSQL): connection = dialect.create_connect_args(u) eq_([['DRIVER={SQL Server};Server=hostspec;Database=database;UI' 'D=username;PWD=password'], {}], connection) - + def test_pymssql_port_setting(self): dialect = pymssql.dialect() @@ -1017,7 +1017,7 @@ class ParseConnectTest(TestBase, AssertsCompiledSQL): [[], {'host': 'somehost:5000', 'password': 'tiger', 'user': 'scott', 'database': 'test'}], connection ) - + @testing.only_on(['mssql+pyodbc', 'mssql+pymssql'], "FreeTDS specific test") def test_bad_freetds_warning(self): engine = engines.testing_engine() @@ -1040,7 +1040,7 @@ class TypesTest(TestBase, AssertsExecutionResults, ComparesTables): def teardown(self): metadata.drop_all() - + @testing.fails_on_everything_except('mssql+pyodbc', 'this is some pyodbc-specific feature') def test_decimal_notation(self): @@ -1424,7 +1424,7 @@ class TypesTest(TestBase, AssertsExecutionResults, ComparesTables): 'NCHAR(1)'), (mssql.MSNChar, [1], {'collation': 'Latin1_General_CI_AS'}, 'NCHAR(1) COLLATE Latin1_General_CI_AS'), - + (mssql.MSString, [], {}, 'VARCHAR(max)'), (mssql.MSString, [1], {}, @@ -1535,7 +1535,7 @@ class TypesTest(TestBase, AssertsExecutionResults, ComparesTables): elif c.name.startswith('int_n'): assert not c.autoincrement, name assert tbl._autoincrement_column is not c, name - + # mxodbc can't handle scope_identity() with DEFAULT VALUES if testing.db.driver == 'mxodbc': @@ -1548,7 +1548,7 @@ class TypesTest(TestBase, AssertsExecutionResults, ComparesTables): : False}), engines.testing_engine(options={'implicit_returning' : True})] - + for counter, engine in enumerate(eng): engine.execute(tbl.insert()) if 'int_y' in tbl.c: @@ -1563,9 +1563,9 @@ class TypesTest(TestBase, AssertsExecutionResults, ComparesTables): class BinaryTest(TestBase, AssertsExecutionResults): """Test the Binary and VarBinary types""" - + __only_on__ = 'mssql' - + @classmethod def setup_class(cls): global binary_table, MyPickleType @@ -1583,7 +1583,7 @@ class BinaryTest(TestBase, AssertsExecutionResults): value.stuff = 'this is the right stuff' return value - binary_table = Table( + binary_table = Table( 'binary_table', MetaData(testing.db), Column('primary_id', Integer, Sequence('binary_id_seq', diff --git a/test/dialect/test_mxodbc.py b/test/dialect/test_mxodbc.py index 36cfc9b08..58ceaf91c 100644 --- a/test/dialect/test_mxodbc.py +++ b/test/dialect/test_mxodbc.py @@ -10,7 +10,7 @@ class MockDBAPI(object): self.log = [] def connect(self, *args, **kwargs): return MockConnection(self) - + class MockConnection(object): def __init__(self, parent): self.parent = parent diff --git a/test/dialect/test_mysql.py b/test/dialect/test_mysql.py index 7d5cffbe2..2fe9e7533 100644 --- a/test/dialect/test_mysql.py +++ b/test/dialect/test_mysql.py @@ -19,7 +19,7 @@ class TypesTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): __only_on__ = 'mysql' __dialect__ = mysql.dialect() - + @testing.uses_deprecated('Manually quoting ENUM value literals') def test_basic(self): meta1 = MetaData(testing.db) @@ -485,22 +485,22 @@ class TypesTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): # if needed, can break out the eq_() just to check for # timestamps that are within a few seconds of "now" # using timedelta. - + now = testing.db.execute("select now()").scalar() - + # TIMESTAMP without NULL inserts current time when passed # NULL. when not passed, generates 0000-00-00 quite # annoyingly. ts_table.insert().execute({'t1':now, 't2':None}) ts_table.insert().execute({'t1':None, 't2':None}) - + eq_( ts_table.select().execute().fetchall(), [(now, now), (None, now)] ) finally: meta.drop_all() - + def test_year(self): """Exercise YEAR.""" @@ -623,7 +623,7 @@ class TypesTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): assert_raises(exc.SQLError, enum_table.insert().execute, e1=None, e2=None, e3=None, e4=None) - + assert_raises(exc.InvalidRequestError, enum_table.insert().execute, e1='c', e2='c', e2generic='c', e3='c', e4='c', e5='c', e5generic='c', e6='c') @@ -663,7 +663,7 @@ class TypesTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): eq_(res, expected) enum_table.drop() - + def test_unicode_enum(self): unicode_engine = utf8_engine() metadata = MetaData(unicode_engine) @@ -696,7 +696,7 @@ class TypesTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): (u'réveillé', u'drôle') #, u'S’il') # eh ? finally: metadata.drop_all() - + def test_enum_compile(self): e1 = Enum('x', 'y', 'z', name='somename') t1 = Table('sometable', MetaData(), Column('somecolumn', e1)) @@ -709,7 +709,7 @@ class TypesTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): "CREATE TABLE sometable (somecolumn " "VARCHAR(1), CHECK (somecolumn IN ('x', " "'y', 'z')))") - + @testing.exclude('mysql', '<', (4,), "3.23 can't handle an ENUM of ''") @testing.uses_deprecated('Manually quoting ENUM value literals') def test_enum_parse(self): @@ -1041,7 +1041,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): eq_( gen(True, ['high_priority', sql.text('sql_cache')]), 'SELECT high_priority sql_cache DISTINCT q') - + def test_backslash_escaping(self): self.assert_compile( sql.column('foo').like('bar', escape='\\'), @@ -1055,7 +1055,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): "foo LIKE %s ESCAPE '\\'", dialect=dialect ) - + def test_limit(self): t = sql.table('t', sql.column('col1'), sql.column('col2')) @@ -1068,13 +1068,13 @@ class SQLTest(TestBase, AssertsCompiledSQL): select([t]).limit(10), "SELECT t.col1, t.col2 FROM t LIMIT %s", {'param_1':10}) - + self.assert_compile( select([t]).offset(10), "SELECT t.col1, t.col2 FROM t LIMIT %s, 18446744073709551615", {'param_1':10} ) - + def test_varchar_raise(self): for type_ in ( String, @@ -1087,7 +1087,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): ): type_ = sqltypes.to_instance(type_) assert_raises(exc.InvalidRequestError, type_.compile, dialect=mysql.dialect()) - + def test_update_limit(self): t = sql.table('t', sql.column('col1'), sql.column('col2')) @@ -1113,7 +1113,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): def test_sysdate(self): self.assert_compile(func.sysdate(), "SYSDATE()") - + def test_cast(self): t = sql.table('t', sql.column('col')) m = mysql @@ -1205,7 +1205,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): for type_, expected in specs: self.assert_compile(cast(t.c.col, type_), expected) - + def test_no_cast_pre_4(self): self.assert_compile( cast(Column('foo', Integer), String), @@ -1218,7 +1218,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): "foo", dialect=dialect ) - + def test_extract(self): t = sql.table('t', sql.column('col1')) @@ -1231,24 +1231,24 @@ class SQLTest(TestBase, AssertsCompiledSQL): self.assert_compile( select([extract('milliseconds', t.c.col1)]), "SELECT EXTRACT(millisecond FROM t.col1) AS anon_1 FROM t") - + def test_too_long_index(self): exp = 'ix_zyrenian_zyme_zyzzogeton_zyzzogeton_zyrenian_zyme_zyz_5cd2' tname = 'zyrenian_zyme_zyzzogeton_zyzzogeton' cname = 'zyrenian_zyme_zyzzogeton_zo' - + t1 = Table(tname, MetaData(), Column(cname, Integer, index=True), ) ix1 = list(t1.indexes)[0] - + self.assert_compile( schema.CreateIndex(ix1), "CREATE INDEX %s " "ON %s (%s)" % (exp, tname, cname), dialect=mysql.dialect() ) - + def test_innodb_autoincrement(self): t1 = Table('sometable', MetaData(), Column('assigned_id', Integer(), primary_key=True, autoincrement=False), @@ -1273,7 +1273,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): class SQLModeDetectionTest(TestBase): __only_on__ = 'mysql' - + def _options(self, modes): def connect(con, record): cursor = con.cursor() @@ -1286,7 +1286,7 @@ class SQLModeDetectionTest(TestBase): ] }) return e - + def test_backslash_escapes(self): engine = self._options(['NO_BACKSLASH_ESCAPES']) c = engine.connect() @@ -1314,7 +1314,7 @@ class SQLModeDetectionTest(TestBase): assert not engine.dialect._backslash_escapes c.close() engine.dispose() - + class RawReflectionTest(TestBase): def setup(self): dialect = mysql.dialect() @@ -1346,7 +1346,7 @@ class ExecutionTest(TestBase): meta.reflect(cx) eq_(cx.dialect._connection_charset, charset) cx.close() - + def test_sysdate(self): d = testing.db.scalar(func.sysdate()) assert isinstance(d, datetime.datetime) @@ -1402,7 +1402,7 @@ class MatchTest(TestBase, AssertsCompiledSQL): self.assert_compile( matchtable.c.title.match('somstr'), "MATCH (matchtable.title) AGAINST (%s IN BOOLEAN MODE)" % format) - + @testing.fails_on('mysql+mysqldb', 'uses format') @testing.fails_on('mysql+oursql', 'uses format') @testing.fails_on('mysql+pyodbc', 'uses format') diff --git a/test/dialect/test_oracle.py b/test/dialect/test_oracle.py index d842c7fc2..a4c3f0a83 100644 --- a/test/dialect/test_oracle.py +++ b/test/dialect/test_oracle.py @@ -120,7 +120,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'col2 FROM sometable ORDER BY ' 'sometable.col2) WHERE ROWNUM <= :ROWNUM_1 ' 'FOR UPDATE') - + s = select([t], for_update=True).limit(10).offset(20).order_by(t.c.col2) self.assert_compile(s, @@ -131,14 +131,14 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'sometable.col2) WHERE ROWNUM <= ' ':ROWNUM_1) WHERE ora_rn > :ora_rn_1 FOR ' 'UPDATE') - - + + def test_long_labels(self): dialect = default.DefaultDialect() dialect.max_identifier_length = 30 - + ora_dialect = oracle.dialect() - + m = MetaData() a_table = Table( 'thirty_characters_table_xxxxxx', @@ -156,7 +156,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): primary_key=True ) ) - + anon = a_table.alias() self.assert_compile(select([other_table, anon]). @@ -189,7 +189,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'thirty_characters_table__1.id = ' 'other_thirty_characters_table_.thirty_char' 'acters_table_id', dialect=ora_dialect) - + def test_outer_join(self): table1 = table('mytable', column('myid', Integer), @@ -283,12 +283,12 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'mytable.name) WHERE ROWNUM <= :ROWNUM_1) ' 'WHERE ora_rn > :ora_rn_1', dialect=oracle.dialect(use_ansi=False)) - + subq = select([table1]).select_from(table1.outerjoin(table2, table1.c.myid == table2.c.otherid)).alias() q = select([table3]).select_from(table3.outerjoin(subq, table3.c.userid == subq.c.myid)) - + self.assert_compile(q, 'SELECT thirdtable.userid, ' 'thirdtable.otherstuff FROM thirdtable ' @@ -299,7 +299,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'mytable.myid = myothertable.otherid) ' 'anon_1 ON thirdtable.userid = anon_1.myid' , dialect=oracle.dialect(use_ansi=True)) - + self.assert_compile(q, 'SELECT thirdtable.userid, ' 'thirdtable.otherstuff FROM thirdtable, ' @@ -310,7 +310,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): '+)) anon_1 WHERE thirdtable.userid = ' 'anon_1.myid(+)', dialect=oracle.dialect(use_ansi=False)) - + q = select([table1.c.name]).where(table1.c.name == 'foo') self.assert_compile(q, 'SELECT mytable.name FROM mytable WHERE ' @@ -326,7 +326,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'mytable.name) AS bar FROM mytable', dialect=oracle.dialect(use_ansi=False)) - + def test_alias_outer_join(self): address_types = table('address_types', column('id'), column('name')) @@ -362,11 +362,11 @@ class CompileTest(TestBase, AssertsCompiledSQL): class CompatFlagsTest(TestBase, AssertsCompiledSQL): __only_on__ = 'oracle' - + def test_ora8_flags(self): def server_version_info(self): return (8, 2, 5) - + dialect = oracle.dialect(dbapi=testing.db.dialect.dbapi) dialect._get_server_version_info = server_version_info @@ -389,7 +389,7 @@ class CompatFlagsTest(TestBase, AssertsCompiledSQL): dialect._get_server_version_info = server_version_info dialect.initialize(testing.db.connect()) assert dialect.implicit_returning - + def test_default_flags(self): """test with no initialization or server version info""" @@ -400,7 +400,7 @@ class CompatFlagsTest(TestBase, AssertsCompiledSQL): self.assert_compile(String(50),"VARCHAR(50 CHAR)",dialect=dialect) self.assert_compile(Unicode(50),"NVARCHAR2(50)",dialect=dialect) self.assert_compile(UnicodeText(),"NCLOB",dialect=dialect) - + def test_ora10_flags(self): def server_version_info(self): return (10, 2, 5) @@ -413,23 +413,23 @@ class CompatFlagsTest(TestBase, AssertsCompiledSQL): self.assert_compile(String(50),"VARCHAR(50 CHAR)",dialect=dialect) self.assert_compile(Unicode(50),"NVARCHAR2(50)",dialect=dialect) self.assert_compile(UnicodeText(),"NCLOB",dialect=dialect) - - + + class MultiSchemaTest(TestBase, AssertsCompiledSQL): __only_on__ = 'oracle' - + @classmethod def setup_class(cls): # currently assuming full DBA privs for the user. # don't really know how else to go here unless # we connect as the other user. - + for stmt in """ create table test_schema.parent( id integer primary key, data varchar2(50) ); - + create table test_schema.child( id integer primary key, data varchar2(50), @@ -441,14 +441,14 @@ create synonym test_schema.ctable for test_schema.child; -- can't make a ref from local schema to the -- remote schema's table without this, --- *and* cant give yourself a grant ! +-- *and* cant give yourself a grant ! -- so we give it to public. ideas welcome. grant references on test_schema.parent to public; grant references on test_schema.child to public; """.split(";"): if stmt.strip(): testing.db.execute(stmt) - + @classmethod def teardown_class(cls): for stmt in """ @@ -459,7 +459,7 @@ drop synonym test_schema.ptable; """.split(";"): if stmt.strip(): testing.db.execute(stmt) - + def test_create_same_names_explicit_schema(self): schema = testing.db.dialect.default_schema_name meta = MetaData(testing.db) @@ -597,7 +597,7 @@ class ConstraintTest(TestBase): ForeignKeyConstraint(['foo_id'], ['foo.id'], onupdate='CASCADE')) assert_raises(exc.SAWarning, bat.create) - + class TypesTest(TestBase, AssertsCompiledSQL): __only_on__ = 'oracle' __dialect__ = oracle.OracleDialect() @@ -620,7 +620,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): b = bindparam("foo", u"hello world!") assert b.type.dialect_impl(dialect).get_dbapi_type(dbapi) == 'STRING' - + @testing.fails_on('+zxjdbc', 'zxjdbc lacks the FIXED_CHAR dbapi type') def test_fixed_char(self): m = MetaData(testing.db) @@ -628,7 +628,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): Column('id', Integer, primary_key=True), Column('data', CHAR(30), nullable=False) ) - + t.create() try: t.insert().execute( @@ -640,17 +640,17 @@ class TypesTest(TestBase, AssertsCompiledSQL): eq_(t.select().where(t.c.data=='value 2').execute().fetchall(), [(2, 'value 2 ')] ) - + m2 = MetaData(testing.db) t2 = Table('t1', m2, autoload=True) assert type(t2.c.data.type) is CHAR eq_(t2.select().where(t2.c.data=='value 2').execute().fetchall(), [(2, 'value 2 ')] ) - + finally: t.drop() - + def test_type_adapt(self): dialect = cx_oracle.dialect() @@ -686,7 +686,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): assert isinstance(x, int) finally: t1.drop() - + @testing.provide_metadata def test_rowid(self): t = Table('t1', metadata, @@ -697,7 +697,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): s1 = select([t]) s2 = select([column('rowid')]).select_from(s1) rowid = s2.scalar() - + # the ROWID type is not really needed here, # as cx_oracle just treats it as a string, # but we want to make sure the ROWID works... @@ -707,7 +707,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): eq_(s3.select().execute().fetchall(), [(5, rowid)] ) - + @testing.fails_on('+zxjdbc', 'Not yet known how to pass values of the ' 'INTERVAL type') @@ -738,7 +738,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): seconds=5743)) finally: metadata.drop_all() - + def test_numerics(self): m = MetaData(testing.db) t1 = Table('t1', m, @@ -750,7 +750,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): Column('numbercol1', oracle.NUMBER(9)), Column('numbercol2', oracle.NUMBER(9, 3)), Column('numbercol3', oracle.NUMBER), - + ) t1.create() try: @@ -764,7 +764,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): numbercol2=14.85, numbercol3=15.76 ) - + m2 = MetaData(testing.db) t2 = Table('t1', m2, autoload=True) @@ -788,17 +788,17 @@ class TypesTest(TestBase, AssertsCompiledSQL): finally: t1.drop() - + @testing.provide_metadata def test_numerics_broken_inspection(self): """Numeric scenarios where Oracle type info is 'broken', returning us precision, scale of the form (0, 0) or (0, -127). We convert to Decimal and let int()/float() processors take over. - + """ - + # this test requires cx_oracle 5 - + foo = Table('foo', metadata, Column('idata', Integer), Column('ndata', Numeric(20, 2)), @@ -807,7 +807,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): Column('fdata', Float()), ) foo.create() - + foo.insert().execute( {'idata':5, 'ndata':decimal.Decimal("45.6"), 'ndata2':decimal.Decimal("45.0"), 'nidata':decimal.Decimal('53'), 'fdata':45.68392}, @@ -822,8 +822,8 @@ class TypesTest(TestBase, AssertsCompiledSQL): fdata FROM foo """ - - + + row = testing.db.execute(stmt).fetchall()[0] eq_([type(x) for x in row], [int, decimal.Decimal, decimal.Decimal, int, float]) eq_( @@ -857,7 +857,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): row, (5, decimal.Decimal('45.6'), 45, 53, decimal.Decimal('45.68392')) ) - + row = testing.db.execute(text(stmt, typemap={ 'idata':Integer(), @@ -870,7 +870,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): eq_(row, (5, decimal.Decimal('45.6'), decimal.Decimal('45'), decimal.Decimal('53'), 45.683920000000001) ) - + stmt = """ SELECT anon_1.idata AS anon_1_idata, @@ -924,7 +924,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): (5, 45.6, 45, 53, decimal.Decimal('45.68392')) ) - + def test_reflect_dates(self): metadata = MetaData(testing.db) Table( @@ -946,10 +946,10 @@ class TypesTest(TestBase, AssertsCompiledSQL): assert isinstance(t1.c.d3.type, TIMESTAMP) assert t1.c.d3.type.timezone assert isinstance(t1.c.d4.type, oracle.INTERVAL) - + finally: metadata.drop_all() - + def test_reflect_raw(self): types_table = Table('all_types', MetaData(testing.db), Column('owner', String(30), primary_key=True), @@ -984,7 +984,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): assert isinstance(res, unicode) finally: metadata.drop_all() - + def test_char_length(self): self.assert_compile(VARCHAR(50),"VARCHAR(50 CHAR)") @@ -994,7 +994,7 @@ class TypesTest(TestBase, AssertsCompiledSQL): self.assert_compile(NVARCHAR(50),"NVARCHAR2(50)") self.assert_compile(CHAR(50),"CHAR(50)") - + metadata = MetaData(testing.db) t1 = Table('t1', metadata, Column("c1", VARCHAR(50)), @@ -1043,24 +1043,24 @@ class TypesTest(TestBase, AssertsCompiledSQL): eq_(row['bindata'].read(), 'this is binary') finally: t.drop(engine) - + class EuroNumericTest(TestBase): """test the numeric output_type_handler when using non-US locale for NLS_LANG.""" - + __only_on__ = 'oracle+cx_oracle' - + def setup(self): self.old_nls_lang = os.environ.get('NLS_LANG', False) os.environ['NLS_LANG'] = "GERMAN" self.engine = testing_engine() - + def teardown(self): if self.old_nls_lang is not False: os.environ['NLS_LANG'] = self.old_nls_lang else: del os.environ['NLS_LANG'] self.engine.dispose() - + @testing.provide_metadata def test_output_type_handler(self): for stmt, exp, kw in [ @@ -1076,8 +1076,8 @@ class EuroNumericTest(TestBase): exp ) assert type(test_exp) is type(exp) - - + + class DontReflectIOTTest(TestBase): """test that index overflow tables aren't included in table_names.""" @@ -1097,10 +1097,10 @@ class DontReflectIOTTest(TestBase): PCTTHRESHOLD 20 OVERFLOW TABLESPACE users """) - + def teardown(self): testing.db.execute("drop table admin_docindex") - + def test_reflect_all(self): m = MetaData(testing.db) m.reflect() @@ -1108,7 +1108,7 @@ class DontReflectIOTTest(TestBase): set(t.name for t in m.tables.values()), set(['admin_docindex']) ) - + class BufferedColumnTest(TestBase, AssertsCompiledSQL): __only_on__ = 'oracle' @@ -1145,7 +1145,7 @@ class BufferedColumnTest(TestBase, AssertsCompiledSQL): class UnsupportedIndexReflectTest(TestBase): __only_on__ = 'oracle' - + def setup(self): global metadata metadata = MetaData(testing.db) @@ -1153,16 +1153,16 @@ class UnsupportedIndexReflectTest(TestBase): Column('data', String(20), primary_key=True) ) metadata.create_all() - + def teardown(self): metadata.drop_all() - + def test_reflect_functional_index(self): testing.db.execute('CREATE INDEX DATA_IDX ON ' 'TEST_INDEX_REFLECT (UPPER(DATA))') m2 = MetaData(testing.db) t2 = Table('test_index_reflect', m2, autoload=True) - + class RoundTripIndexTest(TestBase): __only_on__ = 'oracle' @@ -1236,7 +1236,7 @@ class RoundTripIndexTest(TestBase): metadata.drop_all() - + class SequenceTest(TestBase, AssertsCompiledSQL): def test_basic(self): @@ -1250,8 +1250,8 @@ class SequenceTest(TestBase, AssertsCompiledSQL): seq = Sequence('My_Seq', schema='Some_Schema') assert dialect.identifier_preparer.format_sequence(seq) \ == '"Some_Schema"."My_Seq"' - - + + class ExecuteTest(TestBase): __only_on__ = 'oracle' @@ -1259,7 +1259,7 @@ class ExecuteTest(TestBase): def test_basic(self): eq_(testing.db.execute('/*+ this is a comment */ SELECT 1 FROM ' 'DUAL').fetchall(), [(1, )]) - + def test_sequences_are_integers(self): seq = Sequence('foo_seq') seq.create(testing.db) @@ -1269,17 +1269,17 @@ class ExecuteTest(TestBase): assert type(val) is int finally: seq.drop(testing.db) - + @testing.provide_metadata def test_limit_offset_for_update(self): # oracle can't actually do the ROWNUM thing with FOR UPDATE # very well. - + t = Table('t1', metadata, Column('id', Integer, primary_key=True), Column('data', Integer) ) metadata.create_all() - + t.insert().execute( {'id':1, 'data':1}, {'id':2, 'data':7}, @@ -1287,7 +1287,7 @@ class ExecuteTest(TestBase): {'id':4, 'data':15}, {'id':5, 'data':32}, ) - + # here, we can't use ORDER BY. eq_( t.select(for_update=True).limit(2).execute().fetchall(), @@ -1302,5 +1302,5 @@ class ExecuteTest(TestBase): "ORA-02014", t.select(for_update=True).limit(2).offset(3).execute ) - - + + diff --git a/test/dialect/test_postgresql.py b/test/dialect/test_postgresql.py index cfccb9bb1..a8c63c566 100644 --- a/test/dialect/test_postgresql.py +++ b/test/dialect/test_postgresql.py @@ -56,7 +56,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'RETURNING length(mytable.name) AS length_1' , dialect=dialect) - + def test_insert_returning(self): dialect = postgresql.dialect() table1 = table('mytable', @@ -83,7 +83,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'INSERT INTO mytable (name) VALUES ' '(%(name)s) RETURNING length(mytable.name) ' 'AS length_1', dialect=dialect) - + @testing.uses_deprecated('.*argument is deprecated. Please use ' 'statement.returning.*') def test_old_returning_names(self): @@ -109,7 +109,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): 'INSERT INTO mytable (name) VALUES ' '(%(name)s) RETURNING mytable.myid, ' 'mytable.name', dialect=dialect) - + def test_create_partial_index(self): m = MetaData() tbl = Table('testtbl', m, Column('data', Integer)) @@ -228,7 +228,7 @@ class FloatCoercionTest(TablesTest, AssertsExecutionResults): {'data':52}, {'data':9}, ) - + @testing.resolve_artifact_names def test_float_coercion(self): for type_, result in [ @@ -251,7 +251,7 @@ class FloatCoercionTest(TablesTest, AssertsExecutionResults): ]) ).scalar() eq_(round_decimal(ret, 9), result) - + @testing.provide_metadata def test_arrays(self): t1 = Table('t', metadata, @@ -267,7 +267,7 @@ class FloatCoercionTest(TablesTest, AssertsExecutionResults): row, ([5], [5], [6], [decimal.Decimal("6.4")]) ) - + class EnumTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): __only_on__ = 'postgresql' @@ -296,7 +296,7 @@ class EnumTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): "CREATE TABLE sometable (somecolumn " "VARCHAR(1), CHECK (somecolumn IN ('x', " "'y', 'z')))") - + @testing.fails_on('postgresql+zxjdbc', 'zxjdbc fails on ENUM: column "XXX" is of type ' 'XXX but expression is of type character varying') @@ -319,7 +319,7 @@ class EnumTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): finally: metadata.drop_all() metadata.drop_all() - + def test_name_required(self): metadata = MetaData(testing.db) etype = Enum('four', 'five', 'six', metadata=metadata) @@ -341,7 +341,7 @@ class EnumTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): Enum(u'réveillé', u'drôle', u'S’il', name='onetwothreetype')) ) - + metadata.create_all() try: t1.insert().execute(value=u'drôle') @@ -411,24 +411,24 @@ class EnumTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): metadata.drop_all() assert not testing.db.dialect.has_type(testing.db, 'fourfivesixtype') - + def test_no_support(self): def server_version_info(self): return (8, 2) - + e = engines.testing_engine() dialect = e.dialect dialect._get_server_version_info = server_version_info - + assert dialect.supports_native_enum e.connect() assert not dialect.supports_native_enum - + # initialize is called again on new pool e.dispose() e.connect() assert not dialect.supports_native_enum - + def test_reflection(self): metadata = MetaData(testing.db) @@ -476,14 +476,14 @@ class EnumTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): metadata.drop_all() class NumericInterpretationTest(TestBase): - - + + def test_numeric_codes(self): from sqlalchemy.dialects.postgresql import pg8000, psycopg2, base from sqlalchemy.util.compat import decimal - + for dialect in (pg8000.dialect(), psycopg2.dialect()): - + typ = Numeric().dialect_impl(dialect) for code in base._INT_TYPES + base._FLOAT_TYPES + \ base._DECIMAL_TYPES: @@ -492,7 +492,7 @@ class NumericInterpretationTest(TestBase): if proc is not None: val = proc(val) assert val in (23.7, decimal.Decimal("23.7")) - + class InsertTest(TestBase, AssertsExecutionResults): __only_on__ = 'postgresql' @@ -540,7 +540,7 @@ class InsertTest(TestBase, AssertsExecutionResults): assert_raises_message(exc.DBAPIError, 'violates not-null constraint', eng.execute, t2.insert()) - + def test_sequence_insert(self): table = Table('testtable', metadata, Column('id', Integer, Sequence('my_seq'), primary_key=True), @@ -975,7 +975,7 @@ class DomainReflectionTest(TestBase, AssertsExecutionResults): con.execute("DROP TABLE enum_test") con.execute("DROP DOMAIN enumdomain") con.execute("DROP TYPE testtype") - + def test_table_is_reflected(self): metadata = MetaData(testing.db) table = Table('testtable', metadata, autoload=True) @@ -990,7 +990,7 @@ class DomainReflectionTest(TestBase, AssertsExecutionResults): "Reflected default value didn't equal expected value") assert not table.columns.answer.nullable, \ 'Expected reflected column to not be nullable.' - + def test_enum_domain_is_reflected(self): metadata = MetaData(testing.db) table = Table('enum_test', metadata, autoload=True) @@ -998,7 +998,7 @@ class DomainReflectionTest(TestBase, AssertsExecutionResults): table.c.data.type.enums, ('test', ) ) - + def test_table_is_reflected_test_schema(self): metadata = MetaData(testing.db) table = Table('testtable', metadata, autoload=True, @@ -1356,7 +1356,7 @@ class MiscTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): 'Skipped unsupported reflection of ' 'expression-based index idx3' ]) - + @testing.fails_on('postgresql+pypostgresql', 'pypostgresql bombs on multiple calls') @@ -1370,7 +1370,7 @@ class MiscTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): isolation_level='SERIALIZABLE') eq_(eng.execute('show transaction isolation level').scalar(), 'serializable') - + # check that it stays conn = eng.connect() eq_(conn.execute('show transaction isolation level').scalar(), @@ -1381,7 +1381,7 @@ class MiscTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): eq_(conn.execute('show transaction isolation level').scalar(), 'serializable') conn.close() - + eng = create_engine(testing.db.url, isolation_level='FOO') if testing.db.driver == 'zxjdbc': exception_cls = eng.dialect.dbapi.Error @@ -1399,11 +1399,11 @@ class MiscTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): stmt = text("select cast('hi' as char) as hi", typemap={'hi' : Numeric}) assert_raises(exc.InvalidRequestError, testing.db.execute, stmt) - + class TimezoneTest(TestBase): """Test timezone-aware datetimes. - + psycopg will return a datetime with a tzinfo attached to it, if postgresql returns it. python then will not let you compare a datetime with a tzinfo to a datetime that doesnt have one. this @@ -1526,7 +1526,7 @@ class TimePrecisionTest(TestBase, AssertsCompiledSQL): eq_(t2.c.c6.type.timezone, True) finally: t1.drop() - + class ArrayTest(TestBase, AssertsExecutionResults): __only_on__ = 'postgresql' @@ -1654,7 +1654,7 @@ class ArrayTest(TestBase, AssertsExecutionResults): foo.id = 2 sess.add(foo) sess.flush() - + @testing.provide_metadata def test_tuple_flag(self): assert_raises_message( @@ -1662,7 +1662,7 @@ class ArrayTest(TestBase, AssertsExecutionResults): "mutable must be set to False if as_tuple is True.", postgresql.ARRAY, Integer, mutable=True, as_tuple=True) - + t1 = Table('t1', metadata, Column('id', Integer, primary_key=True), Column('data', postgresql.ARRAY(String(5), as_tuple=True, mutable=False)), @@ -1672,7 +1672,7 @@ class ArrayTest(TestBase, AssertsExecutionResults): testing.db.execute(t1.insert(), id=1, data=["1","2","3"], data2=[5.4, 5.6]) testing.db.execute(t1.insert(), id=2, data=["4", "5", "6"], data2=[1.0]) testing.db.execute(t1.insert(), id=3, data=[["4", "5"], ["6", "7"]], data2=[[5.4, 5.6], [1.0, 1.1]]) - + r = testing.db.execute(t1.select().order_by(t1.c.id)).fetchall() eq_( r, @@ -1687,16 +1687,16 @@ class ArrayTest(TestBase, AssertsExecutionResults): set(row[1] for row in r), set([('1', '2', '3'), ('4', '5', '6'), (('4', '5'), ('6', '7'))]) ) - - - + + + class TimestampTest(TestBase, AssertsExecutionResults): __only_on__ = 'postgresql' def test_timestamp(self): engine = testing.db connection = engine.connect() - + s = select(["timestamp '2007-12-25'"]) result = connection.execute(s).first() eq_(result[0], datetime.datetime(2007, 12, 25, 0, 0)) @@ -1846,15 +1846,15 @@ class ServerSideCursorsTest(TestBase, AssertsExecutionResults): class SpecialTypesTest(TestBase, ComparesTables): """test DDL and reflection of PG-specific types """ - + __only_on__ = 'postgresql' __excluded_on__ = (('postgresql', '<', (8, 3, 0)),) - + @classmethod def setup_class(cls): global metadata, table metadata = MetaData(testing.db) - + # create these types so that we can issue # special SQL92 INTERVAL syntax class y2m(types.UserDefinedType, postgresql.INTERVAL): @@ -1864,7 +1864,7 @@ class SpecialTypesTest(TestBase, ComparesTables): class d2s(types.UserDefinedType, postgresql.INTERVAL): def get_col_spec(self): return "INTERVAL DAY TO SECOND" - + table = Table('sometable', metadata, Column('id', postgresql.PGUuid, primary_key=True), Column('flag', postgresql.PGBit), @@ -1877,31 +1877,31 @@ class SpecialTypesTest(TestBase, ComparesTables): Column('month_interval', d2s()), Column('precision_interval', postgresql.INTERVAL(precision=3)) ) - + metadata.create_all() - + # cheat so that the "strict type check" # works table.c.year_interval.type = postgresql.INTERVAL() table.c.month_interval.type = postgresql.INTERVAL() - + @classmethod def teardown_class(cls): metadata.drop_all() - + def test_reflection(self): m = MetaData(testing.db) t = Table('sometable', m, autoload=True) - + self.assert_tables_equal(table, t, strict_types=True) assert t.c.plain_interval.type.precision is None assert t.c.precision_interval.type.precision == 3 class UUIDTest(TestBase): """Test the bind/return values of the UUID type.""" - + __only_on__ = 'postgresql' - + @testing.requires.python25 @testing.fails_on('postgresql+pg8000', 'No support for UUID type') def test_uuid_string(self): @@ -1913,7 +1913,7 @@ class UUIDTest(TestBase): str(uuid.uuid4()), str(uuid.uuid4()) ) - + @testing.requires.python25 @testing.fails_on('postgresql+pg8000', 'No support for UUID type') def test_uuid_uuid(self): @@ -1925,7 +1925,7 @@ class UUIDTest(TestBase): uuid.uuid4(), uuid.uuid4() ) - + def test_no_uuid_available(self): from sqlalchemy.dialects.postgresql import base uuid_type = base._python_UUID @@ -1937,14 +1937,14 @@ class UUIDTest(TestBase): ) finally: base._python_UUID = uuid_type - + def setup(self): self.conn = testing.db.connect() trans = self.conn.begin() - + def teardown(self): self.conn.close() - + def _test_round_trip(self, utable, value1, value2): utable.create(self.conn) self.conn.execute(utable.insert(), {'data':value1}) @@ -1955,8 +1955,8 @@ class UUIDTest(TestBase): ) eq_(r.fetchone()[0], value2) eq_(r.fetchone(), None) - - + + class MatchTest(TestBase, AssertsCompiledSQL): __only_on__ = 'postgresql' @@ -2063,9 +2063,9 @@ class MatchTest(TestBase, AssertsCompiledSQL): class TupleTest(TestBase): __only_on__ = 'postgresql' - + def test_tuple_containment(self): - + for test, exp in [ ([('a', 'b')], True), ([('a', 'c')], False), diff --git a/test/dialect/test_sqlite.py b/test/dialect/test_sqlite.py index 34f5927ed..e3618f841 100644 --- a/test/dialect/test_sqlite.py +++ b/test/dialect/test_sqlite.py @@ -16,7 +16,7 @@ class TestTypes(TestBase, AssertsExecutionResults): def test_boolean(self): """Test that the boolean only treats 1 as True - + """ meta = MetaData(testing.db) @@ -214,7 +214,7 @@ class DialectTest(TestBase, AssertsExecutionResults): def test_extra_reserved_words(self): """Tests reserved words in identifiers. - + 'true', 'false', and 'column' are undocumented reserved words when used as column identifiers (as of 3.5.1). Covering them here to ensure they remain in place if the dialect's @@ -318,18 +318,18 @@ class DialectTest(TestBase, AssertsExecutionResults): except exc.DBAPIError: pass raise - + def test_pool_class(self): e = create_engine('sqlite+pysqlite://') assert e.pool.__class__ is pool.SingletonThreadPool e = create_engine('sqlite+pysqlite:///:memory:') assert e.pool.__class__ is pool.SingletonThreadPool - + e = create_engine('sqlite+pysqlite:///foo.db') assert e.pool.__class__ is pool.NullPool - - + + def test_dont_reflect_autoindex(self): meta = MetaData(testing.db) t = Table('foo', meta, Column('bar', String, primary_key=True)) @@ -414,7 +414,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): Column('id', Integer, primary_key=True), Column('t1_id', Integer, ForeignKey('master.t1.id')), ) - + # schema->schema, generate REFERENCES with no schema name self.assert_compile( schema.CreateTable(t2), @@ -423,7 +423,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): "t1_id INTEGER, " "PRIMARY KEY (id), " "FOREIGN KEY(t1_id) REFERENCES t1 (id)" - ")" + ")" ) # schema->different schema, don't generate REFERENCES @@ -433,7 +433,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): "id INTEGER NOT NULL, " "t1_id INTEGER, " "PRIMARY KEY (id)" - ")" + ")" ) # same for local schema @@ -443,7 +443,7 @@ class SQLTest(TestBase, AssertsCompiledSQL): "id INTEGER NOT NULL, " "t1_id INTEGER, " "PRIMARY KEY (id)" - ")" + ")" ) diff --git a/test/engine/_base.py b/test/engine/_base.py index 773fa2fea..b55ffcadb 100644 --- a/test/engine/_base.py +++ b/test/engine/_base.py @@ -155,13 +155,13 @@ class AltEngineTest(testing.TestBase): def setup_class(cls): cls.engine = cls.create_engine() super(AltEngineTest, cls).setup_class() - + @classmethod def teardown_class(cls): cls.engine.dispose() cls.engine = None super(AltEngineTest, cls).teardown_class() - + @classmethod def create_engine(cls): raise NotImplementedError diff --git a/test/engine/test_ddlevents.py b/test/engine/test_ddlevents.py index fbe77b9dc..c3914ab37 100644 --- a/test/engine/test_ddlevents.py +++ b/test/engine/test_ddlevents.py @@ -72,7 +72,7 @@ class DDLEventTest(TestBase): canary = self.Canary(table, bind) event.listen(table, 'before_create', canary.before_create) event.listen(table, 'after_create', canary.after_create) - + table.create(bind) assert canary.state == 'after-create' table.drop(bind) @@ -151,7 +151,7 @@ class DDLEventTest(TestBase): def test_metadata_create_both(self): metadata, bind = self.metadata, self.bind canary = self.Canary(metadata, bind) - + event.listen(metadata, 'before_create', canary.before_create) event.listen(metadata, 'after_create', canary.after_create) @@ -259,7 +259,7 @@ class DDLExecutionTest(TestBase): assert 'xyzzy' in strings assert 'fnord' in strings - + def test_metadata(self): metadata, engine = self.metadata, self.engine @@ -320,13 +320,13 @@ class DDLExecutionTest(TestBase): 'after_create', AddConstraint(constraint).execute_if(dialect='postgresql'), ) - + event.listen( users, 'before_drop', DropConstraint(constraint).execute_if(dialect='postgresql'), ) - + metadata.create_all(bind=nonpg_mock) strings = ' '.join(str(x) for x in nonpg_mock.mock) assert 'my_test_constraint' not in strings @@ -339,7 +339,7 @@ class DDLExecutionTest(TestBase): metadata.drop_all(bind=pg_mock) strings = ' '.join(str(x) for x in pg_mock.mock) assert 'my_test_constraint' in strings - + @testing.uses_deprecated(r'See DDLEvents') def test_conditional_constraint_deprecated(self): metadata, users, engine = self.metadata, self.users, self.engine @@ -406,27 +406,27 @@ class DDLExecutionTest(TestBase): @testing.fails_on('postgresql+pg8000', 'pg8000 requires explicit types') def test_platform_escape(self): """test the escaping of % characters in the DDL construct.""" - + default_from = testing.db.dialect.statement_compiler( testing.db.dialect, None).default_from() - + eq_( testing.db.execute( text("select 'foo%something'" + default_from) ).scalar(), 'foo%something' ) - + eq_( testing.db.execute( DDL("select 'foo%%something'" + default_from) ).scalar(), 'foo%something' ) - - - + + + class DDLTest(TestBase, AssertsCompiledSQL): def mock_engine(self): executor = lambda *a, **kw: None diff --git a/test/engine/test_execute.py b/test/engine/test_execute.py index 90d2bc578..9379e207f 100644 --- a/test/engine/test_execute.py +++ b/test/engine/test_execute.py @@ -29,7 +29,7 @@ class ExecuteTest(TestBase): @engines.close_first def teardown(self): testing.db.connect().execute(users.delete()) - + @classmethod def teardown_class(cls): metadata.drop_all() @@ -152,7 +152,7 @@ class ExecuteTest(TestBase): eng.update_execution_options(foo='hoho') conn = eng.contextual_connect() eq_(conn._execution_options['foo'], 'hoho') - + class CompiledCacheTest(TestBase): @classmethod @@ -169,23 +169,23 @@ class CompiledCacheTest(TestBase): @engines.close_first def teardown(self): testing.db.connect().execute(users.delete()) - + @classmethod def teardown_class(cls): metadata.drop_all() - + def test_cache(self): conn = testing.db.connect() cache = {} cached_conn = conn.execution_options(compiled_cache=cache) - + ins = users.insert() cached_conn.execute(ins, {'user_name':'u1'}) cached_conn.execute(ins, {'user_name':'u2'}) cached_conn.execute(ins, {'user_name':'u3'}) assert len(cache) == 1 eq_(conn.execute("select count(*) from users").scalar(), 3) - + class LoggingNameTest(TestBase): def _assert_names_in_execute(self, eng, eng_name, pool_name): eng.execute(select([1])) @@ -203,7 +203,7 @@ class LoggingNameTest(TestBase): 'sqlalchemy.engine.base.Engine', 'sqlalchemy.pool.%s' % eng.pool.__class__.__name__ ) - + def _named_engine(self, **kw): options = { 'logging_name':'myenginename', @@ -229,24 +229,24 @@ class LoggingNameTest(TestBase): logging.getLogger('sqlalchemy.pool') ]: log.removeHandler(self.buf) - + def test_named_logger_names(self): eng = self._named_engine() eq_(eng.logging_name, "myenginename") eq_(eng.pool.logging_name, "mypoolname") - + def test_named_logger_names_after_dispose(self): eng = self._named_engine() eng.execute(select([1])) eng.dispose() eq_(eng.logging_name, "myenginename") eq_(eng.pool.logging_name, "mypoolname") - + def test_unnamed_logger_names(self): eng = self._unnamed_engine() eq_(eng.logging_name, None) eq_(eng.pool.logging_name, None) - + def test_named_logger_execute(self): eng = self._named_engine() self._assert_names_in_execute(eng, "myenginename", "mypoolname") @@ -270,27 +270,27 @@ class LoggingNameTest(TestBase): self._assert_no_name_in_execute(eng) class EchoTest(TestBase): - + def setup(self): self.level = logging.getLogger('sqlalchemy.engine').level logging.getLogger('sqlalchemy.engine').setLevel(logging.WARN) self.buf = logging.handlers.BufferingHandler(100) logging.getLogger('sqlalchemy.engine').addHandler(self.buf) - + def teardown(self): logging.getLogger('sqlalchemy.engine').removeHandler(self.buf) logging.getLogger('sqlalchemy.engine').setLevel(self.level) - + def testing_engine(self): e = engines.testing_engine() - + # do an initial execute to clear out 'first connect' # messages e.execute(select([10])) self.buf.flush() - + return e - + def test_levels(self): e1 = engines.testing_engine() @@ -310,40 +310,40 @@ class EchoTest(TestBase): eq_(e1._should_log_debug(), True) eq_(e1.logger.isEnabledFor(logging.DEBUG), True) eq_(e1.logger.getEffectiveLevel(), logging.DEBUG) - + e1.echo = False eq_(e1._should_log_info(), False) eq_(e1._should_log_debug(), False) eq_(e1.logger.isEnabledFor(logging.INFO), False) eq_(e1.logger.getEffectiveLevel(), logging.WARN) - + def test_echo_flag_independence(self): """test the echo flag's independence to a specific engine.""" e1 = self.testing_engine() e2 = self.testing_engine() - + e1.echo = True e1.execute(select([1])) e2.execute(select([2])) - + e1.echo = False e1.execute(select([3])) e2.execute(select([4])) - + e2.echo = True e1.execute(select([5])) e2.execute(select([6])) - + assert self.buf.buffer[0].getMessage().startswith("SELECT 1") assert self.buf.buffer[2].getMessage().startswith("SELECT 6") assert len(self.buf.buffer) == 4 - + class ResultProxyTest(TestBase): def test_nontuple_row(self): """ensure the C version of BaseRowProxy handles duck-type-dependent rows.""" - + from sqlalchemy.engine import RowProxy class MyList(object): @@ -373,7 +373,7 @@ class ResultProxyTest(TestBase): engine = engines.testing_engine() metadata.bind = engine - + t = Table('t1', metadata, Column('data', String(10)) ) @@ -383,7 +383,7 @@ class ResultProxyTest(TestBase): @property def rowcount(self): assert False - + execution_ctx_cls = engine.dialect.execution_ctx_cls engine.dialect.execution_ctx_cls = type("FakeCtx", (BreakRowcountMixin, @@ -409,13 +409,13 @@ class ResultProxyTest(TestBase): row = RowProxy(object(), ['value'], [None], {'key' : (None, 0), 0: (None, 0)}) assert isinstance(row, collections.Sequence) - + @testing.requires.cextensions def test_row_c_sequence_check(self): import csv import collections from StringIO import StringIO - + metadata = MetaData() metadata.bind = 'sqlite://' users = Table('users', metadata, @@ -470,7 +470,7 @@ class EngineEventsTest(TestBase): ]: event.listen(engine, 'before_execute', execute) event.listen(engine, 'before_cursor_execute', cursor_execute) - + m = MetaData(engine) t1 = Table('t1', m, Column('c1', Integer, primary_key=True), @@ -523,10 +523,10 @@ class EngineEventsTest(TestBase): canary = [] def execute(conn, *args, **kw): canary.append('execute') - + def cursor_execute(conn, *args, **kw): canary.append('cursor_execute') - + engine = engines.testing_engine() event.listen(engine, 'before_execute', execute) event.listen(engine, 'before_cursor_execute', cursor_execute) @@ -548,42 +548,42 @@ class EngineEventsTest(TestBase): def execute(conn, clauseelement, multiparams, params): canary.append('execute') return clauseelement, multiparams, params - + def cursor_execute(conn, cursor, statement, parameters, context, executemany): canary.append('cursor_execute') return statement, parameters - + engine = engines.testing_engine() - + assert_raises( tsa.exc.ArgumentError, event.listen, engine, "begin", tracker("begin"), retval=True ) - + event.listen(engine, "before_execute", execute, retval=True) event.listen(engine, "before_cursor_execute", cursor_execute, retval=True) engine.execute(select([1])) eq_( canary, ['execute', 'cursor_execute'] ) - - - + + + def test_transactional(self): canary = [] def tracker(name): def go(conn, *args, **kw): canary.append(name) return go - + engine = engines.testing_engine() event.listen(engine, 'before_execute', tracker('execute')) event.listen(engine, 'before_cursor_execute', tracker('cursor_execute')) event.listen(engine, 'begin', tracker('begin')) event.listen(engine, 'commit', tracker('commit')) event.listen(engine, 'rollback', tracker('rollback')) - + conn = engine.connect() trans = conn.begin() conn.execute(select([1])) @@ -605,7 +605,7 @@ class EngineEventsTest(TestBase): def go(*args, **kw): canary.append(name) return go - + engine = engines.testing_engine() for name in ['begin', 'savepoint', 'rollback_savepoint', 'release_savepoint', @@ -634,21 +634,21 @@ class EngineEventsTest(TestBase): 'rollback', 'begin_twophase', 'prepare_twophase', 'commit_twophase'] ) - - + + class ProxyConnectionTest(TestBase): """These are the same tests as EngineEventsTest, except using the deprecated ConnectionProxy interface. - + """ - + @testing.uses_deprecated(r'.*Use event.listen') @testing.fails_on('firebird', 'Data type unknown') def test_proxy(self): - + stmts = [] cursor_stmts = [] - + class MyProxy(ConnectionProxy): def execute( self, @@ -672,7 +672,7 @@ class ProxyConnectionTest(TestBase): ): cursor_stmts.append((str(statement), parameters, None)) return execute(cursor, statement, parameters, context) - + def assert_stmts(expected, received): for stmt, params, posn in expected: if not received: @@ -739,7 +739,7 @@ class ProxyConnectionTest(TestBase): # be incorrect assert_stmts(compiled, stmts) assert_stmts(cursor, cursor_stmts) - + @testing.uses_deprecated(r'.*Use event.listen') def test_options(self): canary = [] @@ -758,8 +758,8 @@ class ProxyConnectionTest(TestBase): c3 = c2.execution_options(bar='bat') eq_(c3._execution_options, {'foo':'bar', 'bar':'bat'}) eq_(canary, ['execute', 'cursor_execute']) - - + + @testing.uses_deprecated(r'.*Use event.listen') def test_transactional(self): canary = [] @@ -779,12 +779,12 @@ class ProxyConnectionTest(TestBase): trans = conn.begin() conn.execute(select([1])) trans.commit() - + eq_(canary, [ 'begin', 'execute', 'cursor_execute', 'rollback', 'begin', 'execute', 'cursor_execute', 'commit', ]) - + @testing.uses_deprecated(r'.*Use event.listen') @testing.requires.savepoints @testing.requires.two_phase_transactions @@ -800,7 +800,7 @@ class ProxyConnectionTest(TestBase): engine = engines.testing_engine(options={'proxy':TrackProxy()}) conn = engine.connect() - + trans = conn.begin() trans2 = conn.begin_nested() conn.execute(select([1])) @@ -809,7 +809,7 @@ class ProxyConnectionTest(TestBase): conn.execute(select([1])) trans2.commit() trans.rollback() - + trans = conn.begin_twophase() conn.execute(select([1])) trans.prepare() diff --git a/test/engine/test_parseconnect.py b/test/engine/test_parseconnect.py index 7000549e7..ee9af60bf 100644 --- a/test/engine/test_parseconnect.py +++ b/test/engine/test_parseconnect.py @@ -56,7 +56,7 @@ class DialectImportTest(TestBase): exec ('from sqlalchemy.dialects import %s\ndialect = ' '%s.dialect()' % (name, name), globals()) eq_(dialect.name, name) - + class CreateEngineTest(TestBase): """test that create_engine arguments of different types get propagated properly""" diff --git a/test/engine/test_pool.py b/test/engine/test_pool.py index e9679fee4..4e818894f 100644 --- a/test/engine/test_pool.py +++ b/test/engine/test_pool.py @@ -33,10 +33,10 @@ class MockCursor(object): def close(self): pass -class PoolTestBase(TestBase): +class PoolTestBase(TestBase): def setup(self): pool.clear_managers() - + @classmethod def teardown_class(cls): pool.clear_managers() @@ -48,7 +48,7 @@ class PoolTestBase(TestBase): def _queuepool_dbapi_fixture(self, **kw): dbapi = MockDBAPI() return dbapi, pool.QueuePool(creator=lambda: dbapi.connect('foo.db'), **kw) - + class PoolTest(PoolTestBase): def testmanager(self): manager = pool.manage(MockDBAPI(), use_threadlocal=True) @@ -87,17 +87,17 @@ class PoolTest(PoolTestBase): expected = [(1, )] for row in cursor: eq_(row, expected.pop(0)) - + def test_no_connect_on_recreate(self): def creator(): raise Exception("no creates allowed") - + for cls in (pool.SingletonThreadPool, pool.StaticPool, pool.QueuePool, pool.NullPool, pool.AssertionPool): p = cls(creator=creator) p.dispose() p.recreate() - + mock_dbapi = MockDBAPI() p = cls(creator=mock_dbapi.connect) conn = p.connect() @@ -105,7 +105,7 @@ class PoolTest(PoolTestBase): mock_dbapi.throw_error = True p.dispose() p.recreate() - + def testthreadlocal_del(self): self._do_testthreadlocal(useclose=False) @@ -198,9 +198,9 @@ class PoolEventsTest(PoolTestBase): canary = [] def first_connect(*arg, **kw): canary.append('first_connect') - + event.listen(p, 'first_connect', first_connect) - + return p, canary def _connect_event_fixture(self): @@ -209,7 +209,7 @@ class PoolEventsTest(PoolTestBase): def connect(*arg, **kw): canary.append('connect') event.listen(p, 'connect', connect) - + return p, canary def _checkout_event_fixture(self): @@ -218,7 +218,7 @@ class PoolEventsTest(PoolTestBase): def checkout(*arg, **kw): canary.append('checkout') event.listen(p, 'checkout', checkout) - + return p, canary def _checkin_event_fixture(self): @@ -227,18 +227,18 @@ class PoolEventsTest(PoolTestBase): def checkin(*arg, **kw): canary.append('checkin') event.listen(p, 'checkin', checkin) - + return p, canary - + def test_first_connect_event(self): p, canary = self._first_connect_event_fixture() - + c1 = p.connect() eq_(canary, ['first_connect']) def test_first_connect_event_fires_once(self): p, canary = self._first_connect_event_fixture() - + c1 = p.connect() c2 = p.connect() @@ -264,13 +264,13 @@ class PoolEventsTest(PoolTestBase): def test_connect_event(self): p, canary = self._connect_event_fixture() - + c1 = p.connect() eq_(canary, ['connect']) def test_connect_event_fires_subsequent(self): p, canary = self._connect_event_fixture() - + c1 = p.connect() c2 = p.connect() @@ -280,7 +280,7 @@ class PoolEventsTest(PoolTestBase): p, canary = self._connect_event_fixture() p2 = p.recreate() - + c1 = p.connect() c2 = p2.connect() @@ -294,40 +294,40 @@ class PoolEventsTest(PoolTestBase): c2 = p2.connect() eq_(canary, ['connect', 'connect']) - + def test_checkout_event(self): p, canary = self._checkout_event_fixture() - + c1 = p.connect() eq_(canary, ['checkout']) def test_checkout_event_fires_subsequent(self): p, canary = self._checkout_event_fixture() - + c1 = p.connect() c2 = p.connect() eq_(canary, ['checkout', 'checkout']) def test_checkout_event_on_subsequently_recreated(self): p, canary = self._checkout_event_fixture() - + c1 = p.connect() p2 = p.recreate() c2 = p2.connect() - + eq_(canary, ['checkout', 'checkout']) - + def test_checkin_event(self): p, canary = self._checkin_event_fixture() - + c1 = p.connect() eq_(canary, []) c1.close() eq_(canary, ['checkin']) - + def test_checkin_event_gc(self): p, canary = self._checkin_event_fixture() - + c1 = p.connect() eq_(canary, []) del c1 @@ -336,19 +336,19 @@ class PoolEventsTest(PoolTestBase): def test_checkin_event_on_subsequently_recreated(self): p, canary = self._checkin_event_fixture() - + c1 = p.connect() p2 = p.recreate() c2 = p2.connect() - + eq_(canary, []) - + c1.close() eq_(canary, ['checkin']) - + c2.close() eq_(canary, ['checkin', 'checkin']) - + def test_listen_targets_scope(self): canary = [] def listen_one(*args): @@ -359,7 +359,7 @@ class PoolEventsTest(PoolTestBase): canary.append("listen_three") def listen_four(*args): canary.append("listen_four") - + engine = create_engine(testing.db.url) event.listen(pool.Pool, 'connect', listen_one) event.listen(engine.pool, 'connect', listen_two) @@ -370,10 +370,10 @@ class PoolEventsTest(PoolTestBase): eq_( canary, ["listen_one","listen_four", "listen_two","listen_three"] ) - + def test_listen_targets_per_subclass(self): """test that listen() called on a subclass remains specific to that subclass.""" - + canary = [] def listen_one(*args): canary.append("listen_one") @@ -381,14 +381,14 @@ class PoolEventsTest(PoolTestBase): canary.append("listen_two") def listen_three(*args): canary.append("listen_three") - + event.listen(pool.Pool, 'connect', listen_one) event.listen(pool.QueuePool, 'connect', listen_two) event.listen(pool.SingletonThreadPool, 'connect', listen_three) - + p1 = pool.QueuePool(creator=MockDBAPI().connect) p2 = pool.SingletonThreadPool(creator=MockDBAPI().connect) - + assert listen_one in p1.dispatch.connect assert listen_two in p1.dispatch.connect assert listen_three not in p1.dispatch.connect @@ -400,12 +400,12 @@ class PoolEventsTest(PoolTestBase): eq_(canary, ["listen_one", "listen_two"]) p2.connect() eq_(canary, ["listen_one", "listen_two", "listen_one", "listen_three"]) - + def teardown(self): # TODO: need to get remove() functionality # going pool.Pool.dispatch._clear() - + class DeprecatedPoolListenerTest(PoolTestBase): @testing.uses_deprecated(r".*Use event.listen") def test_listeners(self): @@ -581,7 +581,7 @@ class DeprecatedPoolListenerTest(PoolTestBase): snoop.assert_total(1, 1, 2, 1) c.close() snoop.assert_total(1, 1, 2, 2) - + @testing.uses_deprecated(r".*Use event.listen") def test_listeners_callables(self): def connect(dbapi_con, con_record): @@ -694,7 +694,7 @@ class QueuePoolTest(PoolTestBase): c1.close() lazy_gc() assert not pool._refs - + def test_timeout(self): p = self._queuepool_fixture(pool_size=3, max_overflow=0, @@ -732,7 +732,7 @@ class QueuePoolTest(PoolTestBase): timeouts.append(time.time() - now) continue time.sleep(4) - c1.close() + c1.close() threads = [] for i in xrange(10): @@ -751,7 +751,7 @@ class QueuePoolTest(PoolTestBase): def _test_overflow(self, thread_count, max_overflow): gc_collect() - + dbapi = MockDBAPI() def creator(): time.sleep(.05) @@ -780,7 +780,7 @@ class QueuePoolTest(PoolTestBase): th.join() self.assert_(max(peaks) <= max_overflow) - + lazy_gc() assert not pool._refs @@ -824,7 +824,7 @@ class QueuePoolTest(PoolTestBase): counter, you can fool the counter into giving you a ConnectionFairy with an ambiguous counter. i.e. its not true reference counting.""" - + p = self._queuepool_fixture(pool_size=3, max_overflow=-1, use_threadlocal=True) c1 = p.connect() @@ -918,7 +918,7 @@ class SingletonThreadPoolTest(PoolTestBase): def test_cleanup(self): """test that the pool's connections are OK after cleanup() has been called.""" - + dbapi = MockDBAPI() p = pool.SingletonThreadPool(creator=dbapi.connect, pool_size=3) diff --git a/test/engine/test_reconnect.py b/test/engine/test_reconnect.py index e28985801..ed68fa475 100644 --- a/test/engine/test_reconnect.py +++ b/test/engine/test_reconnect.py @@ -56,7 +56,7 @@ class MockReconnectTest(TestBase): db = tsa.create_engine( 'postgresql://foo:bar@localhost/test', module=dbapi, _initialize=False) - + # monkeypatch disconnect checker db.dialect.is_disconnect = lambda e: isinstance(e, MockDisconnect) @@ -184,11 +184,11 @@ class CursorErrTest(TestBase): def setup(self): global db, dbapi - + class MDBAPI(MockDBAPI): def connect(self, *args, **kwargs): return MConn(self) - + class MConn(MockConnection): def cursor(self): return MCursor(self) @@ -202,16 +202,16 @@ class CursorErrTest(TestBase): db = tsa.create_engine( 'postgresql://foo:bar@localhost/test', module=dbapi, _initialize=False) - + def test_cursor_explode(self): conn = db.connect() result = conn.execute("select foo") result.close() conn.close() - + def teardown(self): db.dispose() - + engine = None class RealReconnectTest(TestBase): def setup(self): @@ -263,14 +263,14 @@ class RealReconnectTest(TestBase): conn = engine.connect() conn.invalidate() conn.invalidate() - + def test_explode_in_initializer(self): engine = engines.testing_engine() def broken_initialize(connection): connection.execute("select fake_stuff from _fake_table") - + engine.dialect.initialize = broken_initialize - + # raises a DBAPIError, not an AttributeError assert_raises(exc.DBAPIError, engine.connect) @@ -279,15 +279,15 @@ class RealReconnectTest(TestBase): engine.dispose() p1 = engine.pool - + def is_disconnect(e): return True - + engine.dialect.is_disconnect = is_disconnect # invalidate() also doesn't screw up assert_raises(exc.DBAPIError, engine.connect) - + # pool was recreated assert engine.pool is not p1 @@ -310,7 +310,7 @@ class RealReconnectTest(TestBase): assert conn.invalidated eq_(conn.execute(select([1])).scalar(), 1) assert not conn.invalidated - + @testing.fails_on('+informixdb', "Wrong error thrown, fix in informixdb?") def test_close(self): @@ -384,7 +384,7 @@ class RecycleTest(TestBase): conn = engine.contextual_connect() eq_(conn.execute(select([1])).scalar(), 1) conn.close() - + meta, table, engine = None, None, None class InvalidateDuringResultTest(TestBase): def setup(self): diff --git a/test/engine/test_reflection.py b/test/engine/test_reflection.py index 5fd18dc81..8e7049b8f 100644 --- a/test/engine/test_reflection.py +++ b/test/engine/test_reflection.py @@ -63,7 +63,7 @@ class ReflectionTest(TestBase, ComparesTables): self.assert_tables_equal(addresses, reflected_addresses) finally: meta.drop_all() - + def test_two_foreign_keys(self): meta = MetaData(testing.db) t1 = Table( @@ -88,12 +88,12 @@ class ReflectionTest(TestBase, ComparesTables): assert t1r.c.t3id.references(t3r.c.id) finally: meta.drop_all() - + def test_nonexistent(self): meta = MetaData(testing.db) assert_raises(sa.exc.NoSuchTableError, Table, 'nonexistent', meta, autoload=True) - + def test_include_columns(self): meta = MetaData(testing.db) foo = Table('foo', meta, *[Column(n, sa.String(30)) @@ -126,7 +126,7 @@ class ReflectionTest(TestBase, ComparesTables): @testing.emits_warning(r".*omitted columns") def test_include_columns_indexes(self): m = MetaData(testing.db) - + t1 = Table('t1', m, Column('a', sa.Integer), Column('b', sa.Integer)) sa.Index('foobar', t1.c.a, t1.c.b) sa.Index('bat', t1.c.a) @@ -148,13 +148,13 @@ class ReflectionTest(TestBase, ComparesTables): def test_autoincrement_col(self): """test that 'autoincrement' is reflected according to sqla's policy. - + Don't mark this test as unsupported for any backend ! - + (technically it fails with MySQL InnoDB since "id" comes before "id2") - + """ - + meta = MetaData(testing.db) t1 = Table('test', meta, Column('id', sa.Integer, primary_key=True), @@ -171,13 +171,13 @@ class ReflectionTest(TestBase, ComparesTables): m2 = MetaData(testing.db) t1a = Table('test', m2, autoload=True) assert t1a._autoincrement_column is t1a.c.id - + t2a = Table('test2', m2, autoload=True) assert t2a._autoincrement_column is t2a.c.id2 - + finally: meta.drop_all() - + def test_unknown_types(self): meta = MetaData(testing.db) t = Table("test", meta, @@ -307,7 +307,7 @@ class ReflectionTest(TestBase, ComparesTables): u4 = Table('users', meta4, Column('id', sa.Integer, key='u_id', primary_key=True), autoload=True) - + a4 = Table( 'addresses', meta4, @@ -326,7 +326,7 @@ class ReflectionTest(TestBase, ComparesTables): assert len(a4.constraints) == 2 finally: meta.drop_all() - + @testing.provide_metadata def test_override_composite_fk(self): """Test double-remove of composite foreign key, when replaced.""" @@ -356,18 +356,18 @@ class ReflectionTest(TestBase, ComparesTables): autoload=True, autoload_with=testing.db ) - + assert b1.c.x is c1 assert b1.c.y is c2 assert f1 in b1.constraints assert len(b1.constraints) == 2 - - - + + + def test_override_keys(self): """test that columns can be overridden with a 'key', and that ForeignKey targeting during reflection still works.""" - + meta = MetaData(testing.db) a1 = Table('a', meta, @@ -390,12 +390,12 @@ class ReflectionTest(TestBase, ComparesTables): assert b2.c.y.references(a2.c.x1) finally: meta.drop_all() - + def test_nonreflected_fk_raises(self): """test that a NoReferencedColumnError is raised when reflecting a table with an FK to another table which has not included the target column in its reflection. - + """ meta = MetaData(testing.db) a1 = Table('a', meta, @@ -412,12 +412,12 @@ class ReflectionTest(TestBase, ComparesTables): m2 = MetaData(testing.db) a2 = Table('a', m2, include_columns=['z'], autoload=True) b2 = Table('b', m2, autoload=True) - + assert_raises(sa.exc.NoReferencedColumnError, a2.join, b2) finally: meta.drop_all() - - + + @testing.exclude('mysql', '<', (4, 1, 1), 'innodb funkiness') def test_override_existing_fk(self): """test that you can override columns and specify new foreign @@ -442,7 +442,7 @@ class ReflectionTest(TestBase, ComparesTables): autoload=True) u2 = Table('users', meta2, autoload=True) s = sa.select([a2]) - + assert s.c.user_id is not None assert len(a2.foreign_keys) == 1 assert len(a2.c.user_id.foreign_keys) == 1 @@ -453,7 +453,7 @@ class ReflectionTest(TestBase, ComparesTables): assert list(a2.c.user_id.foreign_keys)[0].parent \ is a2.c.user_id assert u2.join(a2).onclause.compare(u2.c.id == a2.c.user_id) - + meta2 = MetaData(testing.db) u2 = Table('users', meta2, Column('id', sa.Integer, primary_key=True), autoload=True) @@ -461,7 +461,7 @@ class ReflectionTest(TestBase, ComparesTables): primary_key=True), Column('user_id', sa.Integer, sa.ForeignKey('users.id')), autoload=True) s = sa.select([a2]) - + assert s.c.user_id is not None assert len(a2.foreign_keys) == 1 assert len(a2.c.user_id.foreign_keys) == 1 @@ -472,7 +472,7 @@ class ReflectionTest(TestBase, ComparesTables): assert list(a2.c.user_id.foreign_keys)[0].parent \ is a2.c.user_id assert u2.join(a2).onclause.compare(u2.c.id == a2.c.user_id) - + finally: meta.drop_all() @@ -545,7 +545,7 @@ class ReflectionTest(TestBase, ComparesTables): Column('pkg_id', sa.Integer, sa.ForeignKey('pkgs.pkg_id')), Column('slot', sa.String(128)), ) - + assert_raises_message(sa.exc.InvalidRequestError, "Foreign key assocated with column 'slots.pkg_id' " "could not find table 'pkgs' with which to generate " @@ -642,14 +642,14 @@ class ReflectionTest(TestBase, ComparesTables): else: check_col = 'true' quoter = meta.bind.dialect.identifier_preparer.quote_identifier - + table_b = Table('false', meta, Column('create', sa.Integer, primary_key=True), Column('true', sa.Integer,sa.ForeignKey('select.not')), sa.CheckConstraint('%s <> 1' % quoter(check_col), name='limit') ) - + table_c = Table('is', meta, Column('or', sa.Integer, nullable=False, primary_key=True), Column('join', sa.Integer, nullable=False, primary_key=True), @@ -770,17 +770,17 @@ class ReflectionTest(TestBase, ComparesTables): m2 = MetaData(testing.db) users_v = Table("users_v", m2, autoload=True) addresses_v = Table("email_addresses_v", m2, autoload=True) - + for c1, c2 in zip(users.c, users_v.c): eq_(c1.name, c2.name) self.assert_types_base(c1, c2) - + for c1, c2 in zip(addresses.c, addresses_v.c): eq_(c1.name, c2.name) self.assert_types_base(c1, c2) finally: - dropViews(metadata.bind) - + dropViews(metadata.bind) + @testing.provide_metadata def test_reflect_all_with_views(self): users, addresses = createTables(metadata, None) @@ -788,13 +788,13 @@ class ReflectionTest(TestBase, ComparesTables): metadata.create_all() createViews(metadata.bind, None) m2 = MetaData(testing.db) - + m2.reflect(views=False) eq_( set(m2.tables), set([u'users', u'email_addresses']) ) - + m2 = MetaData(testing.db) m2.reflect(views=True) eq_( @@ -804,7 +804,7 @@ class ReflectionTest(TestBase, ComparesTables): ) finally: dropViews(metadata.bind) - + class CreateDropTest(TestBase): @classmethod @@ -816,7 +816,7 @@ class CreateDropTest(TestBase): sa.Sequence('user_id_seq', optional=True), primary_key=True), Column('user_name',sa.String(40))) - + addresses = Table('email_addresses', metadata, Column('address_id', sa.Integer, sa.Sequence('address_id_seq', optional=True), @@ -846,10 +846,10 @@ class CreateDropTest(TestBase): table_names = [t.name for t in tables] ua = [n for n in table_names if n in ('users', 'email_addresses')] oi = [n for n in table_names if n in ('orders', 'items')] - + eq_(ua, ['users', 'email_addresses']) eq_(oi, ['orders', 'items']) - + def testcheckfirst(self): try: @@ -993,7 +993,7 @@ class SchemaTest(TestBase): schema = engine.dialect.default_schema_name assert bool(schema) - + metadata = MetaData(engine) table1 = Table('table1', metadata, Column('col1', sa.Integer, primary_key=True), @@ -1057,7 +1057,7 @@ class HasSequenceTest(TestBase): schema=test_schema), False) eq_(testing.db.dialect.has_sequence(testing.db, 'user_id_seq'), False) - + # Tests related to engine.reflection @@ -1158,7 +1158,7 @@ class ComponentReflectionTest(TestBase): @testing.requires.schemas def test_get_schema_names(self): insp = Inspector(testing.db) - + self.assert_('test_schema' in insp.get_schema_names()) def test_dialect_initialize(self): @@ -1166,11 +1166,11 @@ class ComponentReflectionTest(TestBase): assert not hasattr(engine.dialect, 'default_schema_name') insp = Inspector(engine) assert hasattr(engine.dialect, 'default_schema_name') - + def test_get_default_schema_name(self): insp = Inspector(testing.db) eq_(insp.default_schema_name, testing.db.dialect.default_schema_name) - + def _test_get_table_names(self, schema=None, table_type='table', order_by=None): meta = MetaData(testing.db) @@ -1287,15 +1287,15 @@ class ComponentReflectionTest(TestBase): eq_(users_pkeys, ['user_id']) addr_cons = insp.get_pk_constraint(addresses.name, schema=schema) - + addr_pkeys = addr_cons['constrained_columns'] eq_(addr_pkeys, ['address_id']) - + @testing.requires.reflects_pk_names def go(): eq_(addr_cons['name'], 'email_ad_pk') go() - + finally: addresses.drop() users.drop() diff --git a/test/engine/test_transaction.py b/test/engine/test_transaction.py index 01a561d7b..e3176a45a 100644 --- a/test/engine/test_transaction.py +++ b/test/engine/test_transaction.py @@ -77,7 +77,7 @@ class TransactionTest(TestBase): result = connection.execute("select * from query_users") assert len(result.fetchall()) == 0 connection.close() - + def test_transaction_container(self): def go(conn, table, data): @@ -93,7 +93,7 @@ class TransactionTest(TestBase): {'user_id': 1, 'user_name': 'user3'}]) eq_(testing.db.execute(users.select()).fetchall(), [(1, 'user1' )]) - + def test_nested_rollback(self): connection = testing.db.connect() try: @@ -138,7 +138,7 @@ class TransactionTest(TestBase): eq_(connection.scalar("select count(*) from query_users"), 0) finally: connection.close() - + def test_nesting(self): connection = testing.db.connect() transaction = connection.begin() @@ -295,7 +295,7 @@ class TransactionTest(TestBase): order_by(users.c.user_id)).fetchall(), [(1, ), (2, ), (5, )]) connection.close() - + @testing.requires.two_phase_transactions @testing.crashes('mysql+oursql', 'Times out in full test runs only, causing ' @@ -350,7 +350,7 @@ class TransactionTest(TestBase): order_by(users.c.user_id)) eq_(result.fetchall(), [('user1', ), ('user4', )]) conn.close() - + class AutoRollbackTest(TestBase): @classmethod @@ -386,7 +386,7 @@ class AutoRollbackTest(TestBase): class ExplicitAutoCommitTest(TestBase): """test the 'autocommit' flag on select() and text() objects. - + Requires PostgreSQL so that we may define a custom function which modifies the database. """ @@ -541,13 +541,13 @@ class TLTransactionTest(TestBase): # ensure tests start with engine closed tlengine.close() - + def test_rollback_no_trans(self): tlengine = create_engine(testing.db.url, strategy="threadlocal") # shouldn't fail tlengine.rollback() - + tlengine.begin() tlengine.rollback() @@ -577,7 +577,7 @@ class TLTransactionTest(TestBase): # shouldn't fail tlengine.prepare() - + def test_connection_close(self): """test that when connections are closed for real, transactions are rolled back and disposed.""" @@ -993,11 +993,11 @@ class ForUpdateTest(TestBase): @testing.requires.independent_connections def test_queued_update(self): """Test SELECT FOR UPDATE with concurrent modifications. - + Runs concurrent modifications on a single row in the users table, with each mutator trying to increment a value stored in user_name. - + """ db = testing.db diff --git a/test/ext/test_associationproxy.py b/test/ext/test_associationproxy.py index fb2f60ff1..c319863c6 100644 --- a/test/ext/test_associationproxy.py +++ b/test/ext/test_associationproxy.py @@ -634,7 +634,7 @@ class ProxyFactoryTest(ListTest): ForeignKey('Parent.id')), Column('foo', String(128)), Column('name', String(128))) - + class CustomProxy(_AssociationList): def __init__( self, @@ -652,7 +652,7 @@ class ProxyFactoryTest(ListTest): setter, parent, ) - + class Parent(object): children = association_proxy('_children', 'name', proxy_factory=CustomProxy, @@ -676,11 +676,11 @@ class ProxyFactoryTest(ListTest): self.metadata = metadata self.session = create_session() self.Parent, self.Child = Parent, Child - + def test_sequence_ops(self): self._test_sequence_ops() - - + + class ScalarTest(TestBase): def test_scalar_proxy(self): metadata = MetaData(testing.db) @@ -1002,7 +1002,7 @@ class ReconstitutionTest(TestBase): class PickleKeyFunc(object): def __init__(self, name): self.name = name - + def __call__(self, obj): return getattr(obj, self.name) @@ -1012,7 +1012,7 @@ class ComparatorTest(_base.MappedTest): run_deletes = None run_setup_mappers = 'once' run_setup_classes = 'once' - + @classmethod def define_tables(cls, metadata): Table('userkeywords', metadata, Column('keyword_id', Integer, diff --git a/test/ext/test_compiler.py b/test/ext/test_compiler.py index 31b893b48..d9bb778db 100644 --- a/test/ext/test_compiler.py +++ b/test/ext/test_compiler.py @@ -28,11 +28,11 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): select([MyThingy('x'), MyThingy('y')]).where(MyThingy() == 5), "SELECT >>x<<, >>y<< WHERE >>MYTHINGY!<< = :MYTHINGY!_1" ) - + def test_types(self): class MyType(TypeEngine): pass - + @compiles(MyType, 'sqlite') def visit_type(type, compiler, **kw): return "SQLITE_FOO" @@ -55,8 +55,8 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): "POSTGRES_FOO", dialect=postgresql.dialect() ) - - + + def test_stateful(self): class MyThingy(ColumnClause): def __init__(self): @@ -101,20 +101,20 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): "INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z " "FROM mytable WHERE mytable.x > :x_1)" ) - + def test_annotations(self): """test that annotated clause constructs use the decorated class' compiler. - + """ t1 = table('t1', column('c1'), column('c2')) - + dispatch = Select._compiler_dispatch try: @compiles(Select) def compile(element, compiler, **kw): return "OVERRIDE" - + s1 = select([t1]) self.assert_compile( s1, "OVERRIDE" @@ -127,22 +127,22 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): Select._compiler_dispatch = dispatch if hasattr(Select, '_compiler_dispatcher'): del Select._compiler_dispatcher - + def test_default_on_existing(self): """test that the existing compiler function remains as 'default' when overriding the compilation of an existing construct.""" - + t1 = table('t1', column('c1'), column('c2')) - + dispatch = Select._compiler_dispatch try: - + @compiles(Select, 'sqlite') def compile(element, compiler, **kw): return "OVERRIDE" - + s1 = select([t1]) self.assert_compile( s1, "SELECT t1.c1, t1.c2 FROM t1", @@ -157,7 +157,7 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): Select._compiler_dispatch = dispatch if hasattr(Select, '_compiler_dispatcher'): del Select._compiler_dispatcher - + def test_dialect_specific(self): class AddThingy(DDLElement): __visit_name__ = 'add_thingy' @@ -211,18 +211,18 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): def test_functions(self): from sqlalchemy.dialects.postgresql import base as postgresql - + class MyUtcFunction(FunctionElement): pass - + @compiles(MyUtcFunction) def visit_myfunc(element, compiler, **kw): return "utcnow()" - + @compiles(MyUtcFunction, 'postgresql') def visit_myfunc(element, compiler, **kw): return "timezone('utc', current_timestamp)" - + self.assert_compile( MyUtcFunction(), "utcnow()", @@ -233,17 +233,17 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): "timezone('utc', current_timestamp)", dialect=postgresql.dialect() ) - + def test_subclasses_one(self): class Base(FunctionElement): name = 'base' - + class Sub1(Base): name = 'sub1' class Sub2(Base): name = 'sub2' - + @compiles(Base) def visit_base(element, compiler, **kw): return element.name @@ -257,11 +257,11 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): 'SELECT FOOsub1, sub2', use_default_dialect=True ) - + def test_subclasses_two(self): class Base(FunctionElement): name = 'base' - + class Sub1(Base): name = 'sub1' @@ -271,10 +271,10 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): class Sub2(Base): name = 'sub2' - + class SubSub1(Sub1): name = 'subsub1' - + self.assert_compile( select([Sub1(), Sub2(), SubSub1()]), 'SELECT sub1, sub2, subsub1', @@ -290,4 +290,3 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): 'SELECT FOOsub1, sub2, FOOsubsub1', use_default_dialect=True ) -
\ No newline at end of file diff --git a/test/ext/test_declarative.py b/test/ext/test_declarative.py index 3daf8c74a..d236cc3ab 100644 --- a/test/ext/test_declarative.py +++ b/test/ext/test_declarative.py @@ -24,7 +24,7 @@ class DeclarativeTestBase(testing.TestBase, testing.AssertsExecutionResults): def teardown(self): clear_mappers() Base.metadata.drop_all() - + class DeclarativeTest(DeclarativeTestBase): def test_basic(self): class User(Base, ComparableEntity): @@ -49,7 +49,7 @@ class DeclarativeTest(DeclarativeTestBase): eq_(Address.__table__.c['id'].name, 'id') eq_(Address.__table__.c['_email'].name, 'email') eq_(Address.__table__.c['_user_id'].name, 'user_id') - + u1 = User(name='u1', addresses=[ Address(email='one'), Address(email='two'), @@ -99,7 +99,7 @@ class DeclarativeTest(DeclarativeTestBase): assert class_mapper(Bar).get_property('some_data').columns[0] \ is t.c.data - + def test_difficult_class(self): """test no getattr() errors with a customized class""" @@ -126,7 +126,7 @@ class DeclarativeTest(DeclarativeTestBase): decl.instrument_declarative(User,{},Base.metadata) - + def test_undefer_column_name(self): # TODO: not sure if there was an explicit # test for this elsewhere @@ -138,7 +138,7 @@ class DeclarativeTest(DeclarativeTestBase): eq_(str(foo), 'foo') eq_(foo.key, 'foo') eq_(foo.name, 'foo') - + def test_recompile_on_othermapper(self): """declarative version of the same test in mappers.py""" @@ -163,7 +163,7 @@ class DeclarativeTest(DeclarativeTestBase): u = User() assert User.addresses assert mapperlib._new_mappers is False - + def test_string_dependency_resolution(self): from sqlalchemy.sql import desc @@ -180,7 +180,7 @@ class DeclarativeTest(DeclarativeTestBase): backref=backref('user', primaryjoin='User.id==Address.user_id', foreign_keys='[Address.user_id]')) - + class Address(Base, ComparableEntity): __tablename__ = 'addresses' @@ -249,7 +249,7 @@ class DeclarativeTest(DeclarativeTestBase): configure_mappers() eq_(str(User.addresses.prop.primaryjoin), 'users.id = addresses.user_id') - + def test_string_dependency_resolution_in_backref(self): class User(Base, ComparableEntity): @@ -271,7 +271,7 @@ class DeclarativeTest(DeclarativeTestBase): configure_mappers() eq_(str(User.addresses.property.primaryjoin), str(Address.user.property.primaryjoin)) - + def test_string_dependency_resolution_tables(self): class User(Base, ComparableEntity): @@ -301,12 +301,12 @@ class DeclarativeTest(DeclarativeTestBase): def test_string_dependency_resolution_schemas(self): Base = decl.declarative_base() - + class User(Base): __tablename__ = 'users' __table_args__ = {'schema':'fooschema'} - + id = Column(Integer, primary_key=True) name = Column(String(50)) props = relationship('Prop', secondary='fooschema.user_to_prop', @@ -327,7 +327,7 @@ class DeclarativeTest(DeclarativeTestBase): Column('prop_id',Integer, ForeignKey('fooschema.props.id')), schema='fooschema') configure_mappers() - + assert class_mapper(User).get_property('props').secondary \ is user_to_prop @@ -370,7 +370,7 @@ class DeclarativeTest(DeclarativeTestBase): eq_(sess.query(User).filter(User.name == 'ed').one(), User(name='ed', addresses=[Address(email='abc'), Address(email='def'), Address(email='xyz')])) - + def test_nice_dependency_error(self): class User(Base): @@ -418,7 +418,7 @@ class DeclarativeTest(DeclarativeTestBase): Base = decl.declarative_base(cls=MyBase) assert hasattr(Base, 'metadata') assert Base().foobar() == "foobar" - + def test_uses_get_on_class_col_fk(self): # test [ticket:1492] @@ -454,27 +454,27 @@ class DeclarativeTest(DeclarativeTestBase): assert d1.master self.assert_sql_count(testing.db, go, 0) - + def test_index_doesnt_compile(self): class User(Base): __tablename__ = 'users' id = Column('id', Integer, primary_key=True) name = Column('name', String(50)) error = relationship("Address") - + i = Index('my_index', User.name) - + # compile fails due to the nonexistent Addresses relationship assert_raises(sa.exc.InvalidRequestError, configure_mappers) - + # index configured assert i in User.__table__.indexes assert User.__table__.c.id not in set(i.columns) assert User.__table__.c.name in set(i.columns) - + # tables create fine Base.metadata.create_all() - + def test_add_prop(self): class User(Base, ComparableEntity): @@ -510,7 +510,7 @@ class DeclarativeTest(DeclarativeTestBase): a1 = sess.query(Address).filter(Address.email == 'two').one() eq_(a1, Address(email='two')) eq_(a1.user, User(name='u1')) - + def test_eager_order_by(self): class Address(Base, ComparableEntity): @@ -613,7 +613,7 @@ class DeclarativeTest(DeclarativeTestBase): __tablename__ = 'foo' __mapper_cls__ = mymapper id = Column(Integer, primary_key=True) - + eq_(Foo.__mapper__.CHECK, True) def test_custom_mapper_argument(self): @@ -648,7 +648,7 @@ class DeclarativeTest(DeclarativeTestBase): assert_raises_message(sa.exc.ArgumentError, 'Mapper Mapper|User|users could not ' 'assemble any primary key', define) - + def test_table_args_bad_format(self): def err(): @@ -661,7 +661,7 @@ class DeclarativeTest(DeclarativeTestBase): assert_raises_message(sa.exc.ArgumentError, 'Tuple form of __table_args__ is ', err) - + def test_table_args_type(self): def err(): class Foo1(Base): @@ -672,9 +672,9 @@ class DeclarativeTest(DeclarativeTestBase): id = Column('id', Integer, primary_key=True) assert_raises_message(sa.exc.ArgumentError, '__table_args__ value must be a tuple, ', err) - + def test_table_args_none(self): - + class Foo2(Base): __tablename__ = 'foo' @@ -682,9 +682,9 @@ class DeclarativeTest(DeclarativeTestBase): id = Column('id', Integer, primary_key=True) assert Foo2.__table__.kwargs == {} - + def test_table_args_dict_format(self): - + class Foo2(Base): __tablename__ = 'foo' @@ -758,14 +758,14 @@ class DeclarativeTest(DeclarativeTestBase): test_needs_autoincrement=True) name = Column('name', String(50)) addresses = relationship('Address', backref='user') - + @declared_attr def address_count(cls): # this doesn't really gain us anything. but if # one is used, lets have it function as expected... return sa.orm.column_property(sa.select([sa.func.count(Address.id)]). where(Address.user_id == cls.id)) - + Base.metadata.create_all() u1 = User(name='u1', addresses=[Address(email='one'), Address(email='two')]) @@ -775,7 +775,7 @@ class DeclarativeTest(DeclarativeTestBase): sess.expunge_all() eq_(sess.query(User).all(), [User(name='u1', address_count=2, addresses=[Address(email='one'), Address(email='two')])]) - + def test_column(self): class User(Base, ComparableEntity): @@ -873,7 +873,7 @@ class DeclarativeTest(DeclarativeTestBase): eq_(u1.name, 'u1') self.assert_sql_count(testing.db, go, 1) - + def test_mapping_to_join(self): users = Table('users', Base.metadata, Column('id', Integer, primary_key=True) @@ -887,16 +887,16 @@ class DeclarativeTest(DeclarativeTestBase): class User(Base): __table__ = usersaddresses __table_args__ = {'primary_key':[users.c.id]} - + # need to use column_property for now user_id = column_property(users.c.id, addresses.c.user_id) address_id = addresses.c.id - + assert User.__mapper__.get_property('user_id').columns[0] \ is users.c.id assert User.__mapper__.get_property('user_id').columns[1] \ is addresses.c.user_id - + def test_synonym_inline(self): class User(Base, ComparableEntity): @@ -1404,14 +1404,14 @@ class DeclarativeInheritanceTest(DeclarativeTestBase): primary_language = Column('primary_language', String(50)) assert class_mapper(Engineer).inherits is class_mapper(Person) - + @testing.fails_if(lambda: True, "Not implemented until 0.7") def test_foreign_keys_with_col(self): """Test that foreign keys that reference a literal 'id' subclass - 'id' attribute behave intuitively. - + 'id' attribute behave intuitively. + See [ticket:1892]. - + """ class Booking(Base): __tablename__ = 'booking' @@ -1430,16 +1430,16 @@ class DeclarativeInheritanceTest(DeclarativeTestBase): primary_key=True) plan_booking_id = Column(Integer, ForeignKey(PlanBooking.id)) - + plan_booking = relationship(PlanBooking, backref='feature_bookings') - + assert FeatureBooking.__table__.c.plan_booking_id.\ references(PlanBooking.__table__.c.id) assert FeatureBooking.__table__.c.id.\ references(Booking.__table__.c.id) - + def test_with_undefined_foreignkey(self): class Parent(Base): @@ -1473,10 +1473,10 @@ class DeclarativeInheritanceTest(DeclarativeTestBase): def test_foreign_keys_with_col(self): """Test that foreign keys that reference a literal 'id' subclass - 'id' attribute behave intuitively. - + 'id' attribute behave intuitively. + See [ticket:1892]. - + """ class Booking(Base): __tablename__ = 'booking' @@ -1495,16 +1495,16 @@ class DeclarativeInheritanceTest(DeclarativeTestBase): primary_key=True) plan_booking_id = Column(Integer, ForeignKey(PlanBooking.id)) - + plan_booking = relationship(PlanBooking, backref='feature_bookings') - + assert FeatureBooking.__table__.c.plan_booking_id.\ references(PlanBooking.__table__.c.id) assert FeatureBooking.__table__.c.id.\ references(Booking.__table__.c.id) - + def test_single_colsonbase(self): """test single inheritance where all the columns are on the base @@ -1562,9 +1562,9 @@ class DeclarativeInheritanceTest(DeclarativeTestBase): def test_single_colsonsub(self): """test single inheritance where the columns are local to their class. - + this is a newer usage. - + """ class Company(Base, ComparableEntity): @@ -1718,7 +1718,7 @@ class DeclarativeInheritanceTest(DeclarativeTestBase): def test_single_fksonsub(self): """test single inheritance with a foreign key-holding column on a subclass. - + """ class Person(Base, ComparableEntity): @@ -2274,28 +2274,28 @@ class DeclarativeMixinTest(DeclarativeTestBase): eq_(obj.name, 'testing') eq_(obj.foo(), 'bar1') eq_(obj.baz, 'fu') - + def test_mixin_overrides(self): """test a mixin that overrides a column on a superclass.""" - + class MixinA(object): foo = Column(String(50)) - + class MixinB(MixinA): foo = Column(Integer) class MyModelA(Base, MixinA): __tablename__ = 'testa' id = Column(Integer, primary_key=True) - + class MyModelB(Base, MixinB): __tablename__ = 'testb' id = Column(Integer, primary_key=True) - + eq_(MyModelA.__table__.c.foo.type.__class__, String) eq_(MyModelB.__table__.c.foo.type.__class__, Integer) - - + + def test_not_allowed(self): class MyMixin: @@ -2347,7 +2347,7 @@ class DeclarativeMixinTest(DeclarativeTestBase): pass eq_(MyModel.__table__.name, 'mymodel') - + def test_classproperty_still_works(self): class MyMixin(object): @classproperty @@ -2359,7 +2359,7 @@ class DeclarativeMixinTest(DeclarativeTestBase): __tablename__ = 'overridden' eq_(MyModel.__table__.name, 'overridden') - + def test_table_name_not_inherited(self): class MyMixin: @@ -2449,13 +2449,13 @@ class DeclarativeMixinTest(DeclarativeTestBase): mapped to a superclass and single-table inheritance subclass. The superclass table gets the column, the subclass shares the MapperProperty. - + """ - + class MyMixin(object): foo = Column('foo', Integer) bar = Column('bar_newname', Integer) - + class General(Base, MyMixin): __tablename__ = 'test' id = Column(Integer, primary_key=True) @@ -2468,19 +2468,19 @@ class DeclarativeMixinTest(DeclarativeTestBase): assert General.bar.prop.columns[0] is General.__table__.c.bar_newname assert len(General.bar.prop.columns) == 1 assert Specific.bar.prop is General.bar.prop - + def test_columns_joined_table_inheritance(self): """Test a column on a mixin with an alternate attribute name, mapped to a superclass and joined-table inheritance subclass. Both tables get the column, in the case of the subclass the two columns are joined under one MapperProperty. - + """ class MyMixin(object): foo = Column('foo', Integer) bar = Column('bar_newname', Integer) - + class General(Base, MyMixin): __tablename__ = 'test' id = Column(Integer, primary_key=True) @@ -2498,7 +2498,7 @@ class DeclarativeMixinTest(DeclarativeTestBase): assert len(Specific.bar.prop.columns) == 2 assert Specific.bar.prop.columns[0] is General.__table__.c.bar_newname assert Specific.bar.prop.columns[1] is Specific.__table__.c.bar_newname - + def test_column_join_checks_superclass_type(self): """Test that the logic which joins subclass props to those of the superclass checks that the superclass property is a column. @@ -2514,7 +2514,7 @@ class DeclarativeMixinTest(DeclarativeTestBase): __tablename__ = 'sub' id = Column(Integer, ForeignKey('test.id'), primary_key=True) type_ = Column('foob', String(50)) - + assert isinstance(General.type_.property, sa.orm.RelationshipProperty) assert Specific.type_.property.columns[0] is Specific.__table__.c.foob @@ -2537,7 +2537,7 @@ class DeclarativeMixinTest(DeclarativeTestBase): assert_raises_message( sa.exc.ArgumentError, "column 'foob' conflicts with property", go ) - + def test_table_args_overridden(self): class MyMixin: @@ -2712,13 +2712,13 @@ class DeclarativeMixinTest(DeclarativeTestBase): if cls.__name__ != 'MyModel': args.pop('polymorphic_on') args['polymorphic_identity'] = cls.__name__ - + return args id = Column(Integer, primary_key=True) - + class MySubModel(MyModel): pass - + eq_( MyModel.__mapper__.polymorphic_on.name, 'type_' @@ -2727,32 +2727,32 @@ class DeclarativeMixinTest(DeclarativeTestBase): eq_(MyModel.__mapper__.always_refresh, True) eq_(MySubModel.__mapper__.always_refresh, True) eq_(MySubModel.__mapper__.polymorphic_identity, 'MySubModel') - + def test_mapper_args_property(self): class MyModel(Base): - + @declared_attr def __tablename__(cls): return cls.__name__.lower() - + @declared_attr def __table_args__(cls): return {'mysql_engine':'InnoDB'} - + @declared_attr def __mapper_args__(cls): args = {} args['polymorphic_identity'] = cls.__name__ return args id = Column(Integer, primary_key=True) - + class MySubModel(MyModel): id = Column(Integer, ForeignKey('mymodel.id'), primary_key=True) class MySubModel2(MyModel): __tablename__ = 'sometable' id = Column(Integer, ForeignKey('mymodel.id'), primary_key=True) - + eq_(MyModel.__mapper__.polymorphic_identity, 'MyModel') eq_(MySubModel.__mapper__.polymorphic_identity, 'MySubModel') eq_(MyModel.__table__.kwargs['mysql_engine'], 'InnoDB') @@ -2760,37 +2760,37 @@ class DeclarativeMixinTest(DeclarativeTestBase): eq_(MySubModel2.__table__.kwargs['mysql_engine'], 'InnoDB') eq_(MyModel.__table__.name, 'mymodel') eq_(MySubModel.__table__.name, 'mysubmodel') - + def test_mapper_args_custom_base(self): """test the @declared_attr approach from a custom base.""" - + class Base(object): @declared_attr def __tablename__(cls): return cls.__name__.lower() - + @declared_attr def __table_args__(cls): return {'mysql_engine':'InnoDB'} - + @declared_attr def id(self): return Column(Integer, primary_key=True) - + Base = decl.declarative_base(cls=Base) - + class MyClass(Base): pass - + class MyOtherClass(Base): pass - + eq_(MyClass.__table__.kwargs['mysql_engine'], 'InnoDB') eq_(MyClass.__table__.name, 'myclass') eq_(MyOtherClass.__table__.name, 'myotherclass') assert MyClass.__table__.c.id.table is MyClass.__table__ assert MyOtherClass.__table__.c.id.table is MyOtherClass.__table__ - + def test_single_table_no_propagation(self): class IdColumn: @@ -2979,7 +2979,7 @@ class DeclarativeMixinTest(DeclarativeTestBase): class ColumnMixin: tada = Column(Integer) - + def go(): class Model(Base, ColumnMixin): @@ -2988,20 +2988,20 @@ class DeclarativeMixinTest(DeclarativeTestBase): Column('data',Integer), Column('id', Integer,primary_key=True)) foo = relationship("Dest") - + assert_raises_message(sa.exc.ArgumentError, "Can't add additional column 'tada' when " "specifying __table__", go) def test_table_in_model_and_different_named_alt_key_column_in_mixin(self): - + # here, the __table__ has a column 'tada'. We disallow # the add of the 'foobar' column, even though it's # keyed to 'tada'. - + class ColumnMixin: tada = Column('foobar', Integer) - + def go(): class Model(Base, ColumnMixin): @@ -3011,7 +3011,7 @@ class DeclarativeMixinTest(DeclarativeTestBase): Column('tada', Integer), Column('id', Integer,primary_key=True)) foo = relationship("Dest") - + assert_raises_message(sa.exc.ArgumentError, "Can't add additional column 'foobar' when " "specifying __table__", go) @@ -3098,10 +3098,10 @@ class DeclarativeMixinPropertyTest(DeclarativeTestBase): def test_doc(self): """test documentation transfer. - + the documentation situation with @declared_attr is problematic. at least see if mapped subclasses get the doc. - + """ class MyMixin(object): @@ -3224,4 +3224,4 @@ class DeclarativeMixinPropertyTest(DeclarativeTestBase): def test_relationship_primryjoin(self): self._test_relationship(True) - + diff --git a/test/ext/test_horizontal_shard.py b/test/ext/test_horizontal_shard.py index b4f60519c..f2b56bca8 100644 --- a/test/ext/test_horizontal_shard.py +++ b/test/ext/test_horizontal_shard.py @@ -29,7 +29,7 @@ class ShardTest(TestBase): def id_generator(ctx): # in reality, might want to use a separate transaction for this. - + c = db1.contextual_connect() nextid = c.execute(ids.select(for_update=True)).scalar() c.execute(ids.update(values={ids.c.nextid : ids.c.nextid + 1})) diff --git a/test/ext/test_hybrid.py b/test/ext/test_hybrid.py index 3dfd4c856..46fc01aae 100644 --- a/test/ext/test_hybrid.py +++ b/test/ext/test_hybrid.py @@ -23,7 +23,7 @@ Base = declarative_base() class UCComparator(hybrid.Comparator): - + def __eq__(self, other): if other is None: return self.expression == None @@ -42,7 +42,7 @@ class A(Base): @value.comparator def value(cls): return UCComparator(cls._value) - + @value.setter def value(self, v): self.value = v @@ -73,7 +73,7 @@ class A(Base): @hybrid.property def value(self): return int(self._value) - + @value.expression def value(cls): return func.foo(cls._value) + cls.bar_value @@ -85,7 +85,7 @@ class A(Base): @hybrid.property def bar_value(cls): return func.bar(cls._value) - + #print A.value #print A.value.__doc__ diff --git a/test/ext/test_mutable.py b/test/ext/test_mutable.py index 1d8208743..9ae28a7fc 100644 --- a/test/ext/test_mutable.py +++ b/test/ext/test_mutable.py @@ -13,10 +13,10 @@ class _MutableDictTestBase(object): @classmethod def _type_fixture(cls): from sqlalchemy.ext.mutable import Mutable - + # needed for pickle support global MutationDict - + class MutationDict(Mutable, dict): @classmethod def coerce(cls, key, value): @@ -26,27 +26,27 @@ class _MutableDictTestBase(object): return Mutable.coerce(key, value) else: return value - + def __getstate__(self): return dict(self) - + def __setstate__(self, dict): self.update(dict) - + def __setitem__(self, key, value): dict.__setitem__(self, key, value) self.change() - + def __delitem__(self, key): dict.__delitem__(self, key) self.change() return MutationDict - + @testing.resolve_artifact_names def setup_mappers(cls): class Foo(_base.BasicEntity): pass - + mapper(Foo, foo) def teardown(self): @@ -54,7 +54,7 @@ class _MutableDictTestBase(object): Mapper.dispatch._clear() ClassManager.dispatch._clear() super(_MutableDictTestBase, self).teardown() - + @testing.resolve_artifact_names def test_in_place_mutation(self): sess = Session() @@ -85,16 +85,16 @@ class MutableWithScalarPickleTest(_MutableDictTestBase, _base.MappedTest): @classmethod def define_tables(cls, metadata): MutationDict = cls._type_fixture() - + Table('foo', metadata, Column('id', Integer, primary_key=True, test_needs_pk=True), Column('data', MutationDict.as_mutable(PickleType)), Column('non_mutable_data', PickleType) ) - + def test_non_mutable(self): self._test_non_mutable() - + class MutableWithScalarJSONTest(_MutableDictTestBase, _base.MappedTest): # json introduced in 2.6 __skip_if__ = lambda : sys.version_info < (2, 6), @@ -116,7 +116,7 @@ class MutableWithScalarJSONTest(_MutableDictTestBase, _base.MappedTest): if value is not None: value = json.loads(value) return value - + MutationDict = cls._type_fixture() Table('foo', metadata, @@ -133,7 +133,7 @@ class MutableAssociationScalarPickleTest(_MutableDictTestBase, _base.MappedTest) def define_tables(cls, metadata): MutationDict = cls._type_fixture() MutationDict.associate_with(PickleType) - + Table('foo', metadata, Column('id', Integer, primary_key=True, test_needs_pk=True), Column('data', PickleType) @@ -163,12 +163,12 @@ class MutableAssociationScalarJSONTest(_MutableDictTestBase, _base.MappedTest): MutationDict = cls._type_fixture() MutationDict.associate_with(JSONEncodedDict) - + Table('foo', metadata, Column('id', Integer, primary_key=True, test_needs_pk=True), Column('data', JSONEncodedDict) ) - + class MutableCompositesTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -186,12 +186,12 @@ class MutableCompositesTest(_base.MappedTest): @classmethod def _type_fixture(cls): - + from sqlalchemy.ext.mutable import Mutable from sqlalchemy.ext.mutable import MutableComposite - + global Point - + class Point(MutableComposite): def __init__(self, x, y): self.x = x @@ -200,24 +200,24 @@ class MutableCompositesTest(_base.MappedTest): def __setattr__(self, key, value): object.__setattr__(self, key, value) self.change() - + def __composite_values__(self): return self.x, self.y - + def __eq__(self, other): return isinstance(other, Point) and \ other.x == self.x and \ other.y == self.y return Point - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): Point = cls._type_fixture() - + class Foo(_base.BasicEntity): pass - + mapper(Foo, foo, properties={ 'data':composite(Point, foo.c.x, foo.c.y) }) @@ -235,4 +235,3 @@ class MutableCompositesTest(_base.MappedTest): eq_(f1.data, Point(3, 5)) -
\ No newline at end of file diff --git a/test/ext/test_sqlsoup.py b/test/ext/test_sqlsoup.py index 66f703068..dfee5748f 100644 --- a/test/ext/test_sqlsoup.py +++ b/test/ext/test_sqlsoup.py @@ -43,7 +43,7 @@ class SQLSoupTest(TestBase): def test_map_to_table_not_string(self): db = sqlsoup.SqlSoup(engine) - + table = Table('users', db._metadata, Column('id', Integer, primary_key=True)) assert_raises_message( exc.ArgumentError, diff --git a/test/lib/assertsql.py b/test/lib/assertsql.py index b206f91fc..4954a0bfe 100644 --- a/test/lib/assertsql.py +++ b/test/lib/assertsql.py @@ -16,10 +16,10 @@ class AssertRule(object): def is_consumed(self): """Return True if this rule has been consumed, False if not. - + Should raise an AssertionError if this rule's condition has definitely failed. - + """ raise NotImplementedError() @@ -32,10 +32,10 @@ class AssertRule(object): def consume_final(self): """Return True if this rule has been consumed. - + Should raise an AssertionError if this rule's condition has not been consumed or has failed. - + """ if self._result is None: @@ -46,18 +46,18 @@ class SQLMatchRule(AssertRule): def __init__(self): self._result = None self._errmsg = "" - + def rule_passed(self): return self._result - + def is_consumed(self): if self._result is None: return False - + assert self._result, self._errmsg - + return True - + class ExactSQL(SQLMatchRule): def __init__(self, sql, params=None): @@ -96,7 +96,7 @@ class ExactSQL(SQLMatchRule): 'Testing for exact statement %r exact params %r, '\ 'received %r with params %r' % (sql, params, _received_statement, _received_parameters) - + class RegexSQL(SQLMatchRule): @@ -194,7 +194,7 @@ class CompiledSQL(SQLMatchRule): # print self._errmsg - + class CountStatements(AssertRule): def __init__(self, count): @@ -216,7 +216,7 @@ class CountStatements(AssertRule): 'desired statement count %d does not match %d' \ % (self.count, self._statement_count) return True - + class AllOf(AssertRule): def __init__(self, *rules): @@ -243,7 +243,7 @@ class AllOf(AssertRule): def consume_final(self): return len(self.rules) == 0 - + def _process_engine_statement(query, context): if util.jython: @@ -255,7 +255,7 @@ def _process_engine_statement(query, context): query = query[:-25] query = re.sub(r'\n', '', query) return query - + def _process_assertion_statement(query, context): paramstyle = context.dialect.paramstyle if paramstyle == 'named': @@ -311,4 +311,4 @@ class SQLAssert(object): executemany) asserter = SQLAssert() - + diff --git a/test/lib/engines.py b/test/lib/engines.py index 60272839b..1c97e23cf 100644 --- a/test/lib/engines.py +++ b/test/lib/engines.py @@ -65,11 +65,11 @@ def rollback_open_connections(fn, *args, **kw): @decorator def close_first(fn, *args, **kw): """Decorator that closes all connections before fn execution.""" - + testing_reaper.close_all() fn(*args, **kw) - - + + @decorator def close_open_connections(fn, *args, **kw): """Decorator that closes all connections after fn execution.""" @@ -88,7 +88,7 @@ def all_dialects(exclude=None): if not mod: mod = getattr(__import__('sqlalchemy.databases.%s' % name).databases, name) yield mod.dialect() - + class ReconnectFixture(object): def __init__(self, dbapi): self.dbapi = dbapi @@ -135,11 +135,11 @@ def testing_engine(url=None, options=None): event.listen(engine, 'after_execute', asserter.execute) event.listen(engine, 'after_cursor_execute', asserter.cursor_execute) event.listen(engine.pool, 'checkout', testing_reaper.checkout) - + # may want to call this, results # in first-connect initializers #engine.connect() - + return engine def utf8_engine(url=None, options=None): @@ -165,18 +165,18 @@ def utf8_engine(url=None, options=None): def mock_engine(dialect_name=None): """Provides a mocking engine based on the current testing.db. - + This is normally used to test DDL generation flow as emitted by an Engine. - + It should not be used in other cases, as assert_compile() and assert_sql_execution() are much better choices with fewer moving parts. - + """ - + from sqlalchemy import create_engine - + if not dialect_name: dialect_name = config.db.name @@ -186,7 +186,7 @@ def mock_engine(dialect_name=None): def assert_sql(stmts): recv = [re.sub(r'[\n\t]', '', str(s)) for s in buffer] assert recv == stmts, recv - + engine = create_engine(dialect_name + '://', strategy='mock', executor=executor) assert not hasattr(engine, 'mock') @@ -212,7 +212,7 @@ class ReplayableSession(object): #for t in ('FunctionType', 'BuiltinFunctionType', # 'MethodType', 'BuiltinMethodType', # 'LambdaType', )]) - + # Py2K for t in ('FunctionType', 'BuiltinFunctionType', 'MethodType', 'BuiltinMethodType', @@ -243,11 +243,11 @@ class ReplayableSession(object): else: buffer.append(result) return result - + @property def _sqla_unwrap(self): return self._subject - + def __getattribute__(self, key): try: return object.__getattribute__(self, key) @@ -280,11 +280,11 @@ class ReplayableSession(object): return self else: return result - + @property def _sqla_unwrap(self): return None - + def __getattribute__(self, key): try: return object.__getattribute__(self, key) diff --git a/test/lib/entities.py b/test/lib/entities.py index 0ec677eea..1b24e73b7 100644 --- a/test/lib/entities.py +++ b/test/lib/entities.py @@ -50,7 +50,7 @@ class ComparableEntity(BasicEntity): self_key = sa.orm.attributes.instance_state(self).key except sa.orm.exc.NO_STATE: self_key = None - + if other is None: a = self b = other diff --git a/test/lib/pickleable.py b/test/lib/pickleable.py index 9794e424d..acc07ceba 100644 --- a/test/lib/pickleable.py +++ b/test/lib/pickleable.py @@ -33,11 +33,11 @@ class OldSchool: def __eq__(self, other): return other.__class__ is self.__class__ and other.x==self.x and other.y==self.y -class OldSchoolWithoutCompare: +class OldSchoolWithoutCompare: def __init__(self, x, y): self.x = x self.y = y - + class BarWithoutCompare(object): def __init__(self, x, y): self.x = x diff --git a/test/lib/profiling.py b/test/lib/profiling.py index 8676adf01..bac9e549f 100644 --- a/test/lib/profiling.py +++ b/test/lib/profiling.py @@ -41,7 +41,7 @@ def profiled(target=None, **target_opts): all_targets.add(target) filename = "%s.prof" % target - + @decorator def decorate(fn, *args, **kw): if (target not in profile_config['targets'] and @@ -50,7 +50,7 @@ def profiled(target=None, **target_opts): elapsed, load_stats, result = _profile( filename, fn, *args, **kw) - + graphic = target_opts.get('graphic', profile_config['graphic']) if graphic: os.system("runsnake %s" % filename) @@ -68,17 +68,17 @@ def profiled(target=None, **target_opts): stats.print_stats(limit) else: stats.print_stats() - + print_callers = target_opts.get('print_callers', profile_config['print_callers']) if print_callers: stats.print_callers() - + print_callees = target_opts.get('print_callees', profile_config['print_callees']) if print_callees: stats.print_callees() - + os.unlink(filename) return result return decorate @@ -113,7 +113,7 @@ def function_call_count(count=None, versions={}, variance=0.05): cextension = True except ImportError: cextension = False - + while version_info: version = '.'.join([str(v) for v in version_info]) if cextension and (version + "+cextension") in versions: @@ -129,7 +129,7 @@ def function_call_count(count=None, versions={}, variance=0.05): if count is None: print "Warning: no function call count specified for version: '%s'" % py_version return lambda fn: fn - + @decorator def decorate(fn, *args, **kw): try: diff --git a/test/lib/requires.py b/test/lib/requires.py index 222dc93f6..993a1546f 100644 --- a/test/lib/requires.py +++ b/test/lib/requires.py @@ -54,7 +54,7 @@ def boolean_col_expressions(fn): no_support('maxdb', 'FIXME: verify not supported by database'), no_support('informix', 'not supported by database'), ) - + def identity(fn): """Target database must support GENERATED AS IDENTITY or a facsimile. @@ -99,19 +99,19 @@ def row_triggers(fn): # no access to same table no_support('mysql', 'requires SUPER priv'), exclude('mysql', '<', (5, 0, 10), 'not supported by database'), - + # huh? TODO: implement triggers for PG tests, remove this - no_support('postgresql', 'PG triggers need to be implemented for tests'), + no_support('postgresql', 'PG triggers need to be implemented for tests'), ) def correlated_outer_joins(fn): """Target must support an outer join to a subquery which correlates to the parent.""" - + return _chain_decorators_on( fn, no_support('oracle', 'Raises "ORA-01799: a column may not be outer-joined to a subquery"') ) - + def savepoints(fn): """Target database must support savepoints.""" return _chain_decorators_on( @@ -126,21 +126,21 @@ def savepoints(fn): def denormalized_names(fn): """Target database must have 'denormalized', i.e. UPPERCASE as case insensitive names.""" - + return skip_if( lambda: not testing.db.dialect.requires_name_normalize, "Backend does not require denomralized names." )(fn) - + def schemas(fn): """Target database must support external schemas, and have one named 'test_schema'.""" - + return _chain_decorators_on( fn, no_support('sqlite', 'no schema support'), no_support('firebird', 'no schema support') ) - + def sequences(fn): """Target database must support SEQUENCEs.""" return _chain_decorators_on( @@ -164,7 +164,7 @@ def update_nowait(fn): no_support('sqlite', 'no FOR UPDATE NOWAIT support'), no_support('sybase', 'no FOR UPDATE NOWAIT support'), ) - + def subqueries(fn): """Target database must support subqueries.""" return _chain_decorators_on( @@ -198,7 +198,7 @@ def offset(fn): fn, fails_on('sybase', 'no support for OFFSET or equivalent'), ) - + def returning(fn): return _chain_decorators_on( fn, @@ -209,7 +209,7 @@ def returning(fn): no_support('sybase', 'not supported by database'), no_support('informix', 'not supported by database'), ) - + def two_phase_transactions(fn): """Target database must support two-phase transactions.""" return _chain_decorators_on( @@ -257,13 +257,13 @@ def cextensions(fn): fn, skip_if(lambda: not _has_cextensions(), "C extensions not installed") ) - + def dbapi_lastrowid(fn): return _chain_decorators_on( fn, fails_on_everything_except('mysql+mysqldb', 'mysql+oursql', 'sqlite+pysqlite') ) - + def sane_multi_rowcount(fn): return _chain_decorators_on( fn, @@ -283,7 +283,7 @@ def reflects_pk_names(fn): fn, fails_on_everything_except('postgresql', 'oracle') ) - + def python2(fn): return _chain_decorators_on( fn, @@ -317,7 +317,7 @@ def _has_cextensions(): return True except ImportError: return False - + def _has_sqlite(): from sqlalchemy import create_engine try: diff --git a/test/lib/schema.py b/test/lib/schema.py index 614e5863e..b4aabfe76 100644 --- a/test/lib/schema.py +++ b/test/lib/schema.py @@ -76,4 +76,4 @@ def _truncate_name(dialect, name): return name[0:max(dialect.max_identifier_length - 6, 0)] + "_" + hex(hash(name) % 64)[2:] else: return name - + diff --git a/test/lib/testing.py b/test/lib/testing.py index 6a2c62959..d6338cf10 100644 --- a/test/lib/testing.py +++ b/test/lib/testing.py @@ -18,7 +18,7 @@ from sqlalchemy import exc as sa_exc, util, types as sqltypes, schema, \ from sqlalchemy.engine import default from nose import SkipTest - + _ops = { '<': operator.lt, '>': operator.gt, '==': operator.eq, @@ -90,9 +90,9 @@ def db_spec(*dbs): return engine.name in dialects or \ engine.driver in drivers or \ (engine.name, engine.driver) in specs - + return check - + def fails_on(dbs, reason): """Mark a test as expected to fail on the specified database @@ -105,7 +105,7 @@ def fails_on(dbs, reason): """ spec = db_spec(dbs) - + @decorator def decorate(fn, *args, **kw): if not spec(config.db): @@ -132,7 +132,7 @@ def fails_on_everything_except(*dbs): """ spec = db_spec(*dbs) - + @decorator def decorate(fn, *args, **kw): if spec(config.db): @@ -211,7 +211,7 @@ def only_on(dbs, reason): print >> sys.stderr, msg return True return decorate - + def exclude(db, op, spec, reason): """Mark a test as unsupported by specific database server versions. @@ -225,7 +225,7 @@ def exclude(db, op, spec, reason): """ carp = _should_carp_about_exclusion(reason) - + @decorator def decorate(fn, *args, **kw): if _is_excluded(db, op, spec): @@ -283,7 +283,7 @@ def _server_version(bind=None): if bind is None: bind = config.db - + # force metadata to be retrieved conn = bind.connect() version = getattr(bind.dialect, 'server_version_info', ()) @@ -294,7 +294,7 @@ def skip_if(predicate, reason=None): """Skip a test if predicate is true.""" reason = reason or predicate.__name__ carp = _should_carp_about_exclusion(reason) - + @decorator def decorate(fn, *args, **kw): if predicate(): @@ -320,7 +320,7 @@ def emits_warning(*messages): # and may work on non-CPython if they keep to the spirit of # warnings.showwarning's docstring. # - update: jython looks ok, it uses cpython's module - + @decorator def decorate(fn, *args, **kw): # todo: should probably be strict about this, too @@ -350,7 +350,7 @@ def emits_warning_on(db, *warnings): warnings.filterwarnings(). """ spec = db_spec(db) - + @decorator def decorate(fn, *args, **kw): if isinstance(db, basestring): @@ -369,16 +369,16 @@ def emits_warning_on(db, *warnings): def assert_warnings(fn, warnings): """Assert that each of the given warnings are emitted by fn.""" - + orig_warn = util.warn def capture_warnings(*args, **kw): orig_warn(*args, **kw) popwarn = warnings.pop(0) eq_(args[0], popwarn) util.warn = util.langhelpers.warn = capture_warnings - + return emits_warning()(fn)() - + def uses_deprecated(*messages): """Mark a test as immune from fatal deprecation warnings. @@ -419,7 +419,7 @@ def uses_deprecated(*messages): def testing_warn(msg, stacklevel=3): """Replaces sqlalchemy.util.warn during tests.""" - + filename = "test.lib.testing" lineno = 1 if isinstance(msg, basestring): @@ -429,9 +429,9 @@ def testing_warn(msg, stacklevel=3): def resetwarnings(): """Reset warning behavior to testing defaults.""" - + util.warn = util.langhelpers.warn = testing_warn - + warnings.filterwarnings('ignore', category=sa_exc.SAPendingDeprecationWarning) warnings.filterwarnings('error', category=sa_exc.SADeprecationWarning) @@ -440,17 +440,17 @@ def resetwarnings(): def global_cleanup_assertions(): """Check things that have to be finalized at the end of a test suite. - + Hardcoded at the moment, a modular system can be built here to support things like PG prepared transactions, tables all dropped, etc. - + """ testutil.lazy_gc() assert not pool._refs - - + + def against(*queries): """Boolean predicate, compares to testing database configuration. @@ -523,7 +523,7 @@ def assert_raises(except_cls, callable_, *args, **kw): success = False except except_cls, e: success = True - + # assert outside the block so it works for AssertionError too ! assert success, "Callable did not raise an exception" @@ -537,7 +537,7 @@ def assert_raises_message(except_cls, msg, callable_, *args, **kwargs): def fail(msg): assert False, msg - + def fixture(table, columns, *rows): """Insert data into table after creation.""" def onload(event, schema_item, connection): @@ -624,34 +624,34 @@ class TestBase(object): def assert_(self, val, msg=None): assert val, msg - + class AssertsCompiledSQL(object): def assert_compile(self, clause, result, params=None, checkparams=None, dialect=None, use_default_dialect=False): if use_default_dialect: dialect = default.DefaultDialect() - + if dialect is None: dialect = getattr(self, '__dialect__', None) kw = {} if params is not None: kw['column_keys'] = params.keys() - + if isinstance(clause, orm.Query): context = clause._compile_context() context.statement.use_labels = True clause = context.statement - + c = clause.compile(dialect=dialect, **kw) param_str = repr(getattr(c, 'params', {})) # Py3K #param_str = param_str.encode('utf-8').decode('ascii', 'ignore') - + print "\nSQL String:\n" + str(c) + param_str - + cc = re.sub(r'[\n\t]', '', str(c)) - + eq_(cc, result, "%r != %r on dialect %r" % (cc, result, dialect)) if checkparams is not None: @@ -665,7 +665,7 @@ class ComparesTables(object): assert reflected_c is reflected_table.c[c.name] eq_(c.primary_key, reflected_c.primary_key) eq_(c.nullable, reflected_c.nullable) - + if strict_types: assert type(reflected_c.type) is type(c.type), \ "Type '%s' doesn't correspond to type '%s'" % (reflected_c.type, c.type) @@ -683,7 +683,7 @@ class ComparesTables(object): assert len(table.primary_key) == len(reflected_table.primary_key) for c in table.primary_key: assert reflected_table.primary_key.columns[c.name] is not None - + def assert_types_base(self, c1, c2): assert c1.type._compare_type_affinity(c2.type),\ "On column %r, type '%s' doesn't correspond to type '%s'" % \ @@ -770,13 +770,13 @@ class AssertsExecutionResults(object): assertsql.asserter.statement_complete() finally: assertsql.asserter.clear_rules() - + def assert_sql(self, db, callable_, list_, with_sequences=None): if with_sequences is not None and config.db.name in ('firebird', 'oracle', 'postgresql'): rules = with_sequences else: rules = list_ - + newrules = [] for rule in rules: if isinstance(rule, dict): @@ -786,7 +786,7 @@ class AssertsExecutionResults(object): else: newrule = assertsql.ExactSQL(*rule) newrules.append(newrule) - + self.assert_sql_execution(db, callable_, *newrules) def assert_sql_count(self, db, callable_, count): diff --git a/test/lib/util.py b/test/lib/util.py index 4c9892852..b512cf6b0 100644 --- a/test/lib/util.py +++ b/test/lib/util.py @@ -13,7 +13,7 @@ if jython: gc.collect() gc.collect() return 0 - + # "lazy" gc, for VM's that don't GC on refcount == 0 lazy_gc = gc_collect @@ -34,48 +34,48 @@ def picklers(): # end Py2K import pickle picklers.add(pickle) - + # yes, this thing needs this much testing for pickle in picklers: for protocol in -1, 0, 1, 2: yield pickle.loads, lambda d:pickle.dumps(d, protocol) - - + + def round_decimal(value, prec): if isinstance(value, float): return round(value, prec) - + # can also use shift() here but that is 2.6 only return (value * decimal.Decimal("1" + "0" * prec)).to_integral(decimal.ROUND_FLOOR) / \ pow(10, prec) - + class RandomSet(set): def __iter__(self): l = list(set.__iter__(self)) random.shuffle(l) return iter(l) - + def pop(self): index = random.randint(0, len(self) - 1) item = list(set.__iter__(self))[index] self.remove(item) return item - + def union(self, other): return RandomSet(set.union(self, other)) - + def difference(self, other): return RandomSet(set.difference(self, other)) - + def intersection(self, other): return RandomSet(set.intersection(self, other)) - + def copy(self): return RandomSet(self) - + def conforms_partial_ordering(tuples, sorted_elements): """True if the given sorting conforms to the given partial ordering.""" - + deps = defaultdict(set) for parent, child in tuples: deps[parent].add(child) @@ -101,7 +101,7 @@ def all_partial_orderings(tuples, elements): if not subset.intersection(edges[elem]): for sub_ordering in _all_orderings(subset): yield [elem] + sub_ordering - + return iter(_all_orderings(elements)) @@ -114,7 +114,7 @@ def function_named(fn, name): This function should be phased out as much as possible in favor of @decorator. Tests that "generate" many named tests should be modernized. - + """ try: fn.__name__ = name diff --git a/test/orm/_base.py b/test/orm/_base.py index 345009d40..ef1ec33f1 100644 --- a/test/orm/_base.py +++ b/test/orm/_base.py @@ -183,7 +183,7 @@ class MappedTest(ORMTest): if name[0].isupper: delattr(cls, name) del cls.classes[name] - + @classmethod def _load_fixtures(cls): headers, rows = {}, {} diff --git a/test/orm/_fixtures.py b/test/orm/_fixtures.py index 8f128c287..3c7d0aa57 100644 --- a/test/orm/_fixtures.py +++ b/test/orm/_fixtures.py @@ -169,7 +169,7 @@ composite_pk_table = fixture_table( Table('composite_pk_table', fixture_metadata, Column('i', Integer, primary_key=True), Column('j', Integer, primary_key=True), - Column('k', Integer, nullable=False), + Column('k', Integer, nullable=False), ), ('i', 'j', 'k'), (1, 2, 3), @@ -218,7 +218,7 @@ class Node(Base): class CompositePk(Base): pass - + class FixtureTest(_base.MappedTest): """A MappedTest pre-configured for fixtures. @@ -378,7 +378,7 @@ class CannedResults(object): keywords=[]), Item(id=5, keywords=[])] - + @property def user_item_keyword_result(self): item1, item2, item3, item4, item5 = \ @@ -420,6 +420,6 @@ class CannedResults(object): items=[item1, item5])]), User(id=10, orders=[])] return user_result - + FixtureTest.static = CannedResults() diff --git a/test/orm/inheritance/test_abc_inheritance.py b/test/orm/inheritance/test_abc_inheritance.py index 08ab28a08..d370ec9cb 100644 --- a/test/orm/inheritance/test_abc_inheritance.py +++ b/test/orm/inheritance/test_abc_inheritance.py @@ -11,9 +11,9 @@ def produce_test(parent, child, direction): """produce a testcase for A->B->C inheritance with a self-referential relationship between two of the classes, using either one-to-many or many-to-one. - + the old "no discriminator column" pattern is used. - + """ class ABCTest(_base.MappedTest): @classmethod diff --git a/test/orm/inheritance/test_basic.py b/test/orm/inheritance/test_basic.py index 095434999..df7958b2f 100644 --- a/test/orm/inheritance/test_basic.py +++ b/test/orm/inheritance/test_basic.py @@ -84,7 +84,7 @@ class PolymorphicOnNotLocalTest(_base.MappedTest): Column('id', Integer, primary_key=True), Column('y', String(10)), Column('xid', ForeignKey('t1.id'))) - + @testing.resolve_artifact_names def test_bad_polymorphic_on(self): class InterfaceBase(object): @@ -126,8 +126,8 @@ class PolymorphicOnNotLocalTest(_base.MappedTest): "polymorphic loads will not function properly", go ) - - + + class FalseDiscriminatorTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -135,7 +135,7 @@ class FalseDiscriminatorTest(_base.MappedTest): t1 = Table('t1', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('type', Boolean, nullable=False)) - + def test_false_on_sub(self): class Foo(object):pass class Bar(Foo):pass @@ -161,7 +161,7 @@ class FalseDiscriminatorTest(_base.MappedTest): assert d1.type is False sess.expunge_all() assert sess.query(Ding).one() is not None - + class PolymorphicSynonymTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -175,7 +175,7 @@ class PolymorphicSynonymTest(_base.MappedTest): Column('id', Integer, ForeignKey('t1.id'), primary_key=True), Column('data', String(10), nullable=False)) - + def test_polymorphic_synonym(self): class T1(_fixtures.Base): def info(self): @@ -183,9 +183,9 @@ class PolymorphicSynonymTest(_base.MappedTest): def _set_info(self, x): self._info = x info = property(info, _set_info) - + class T2(T1):pass - + mapper(T1, t1, polymorphic_on=t1.c.type, polymorphic_identity='t1', properties={ 'info':synonym('_info', map_column=True) @@ -200,12 +200,12 @@ class PolymorphicSynonymTest(_base.MappedTest): sess.expunge_all() eq_(sess.query(T2).filter(T2.info=='at2').one(), at2) eq_(at2.info, "THE INFO IS:at2") - + class PolymorphicAttributeManagementTest(_base.MappedTest): """Test polymorphic_on can be assigned, can be mirrored, etc.""" run_setup_mappers = 'once' - + @classmethod def define_tables(cls, metadata): Table('table_a', metadata, @@ -222,7 +222,7 @@ class PolymorphicAttributeManagementTest(_base.MappedTest): Column('id', Integer, ForeignKey('table_b.id'), primary_key=True) ) - + @classmethod @testing.resolve_artifact_names def setup_classes(cls): @@ -232,7 +232,7 @@ class PolymorphicAttributeManagementTest(_base.MappedTest): pass class C(B): pass - + mapper(A, table_a, polymorphic_on=table_a.c.class_name, polymorphic_identity='a') @@ -241,7 +241,7 @@ class PolymorphicAttributeManagementTest(_base.MappedTest): polymorphic_identity='b') mapper(C, table_c, inherits=B, polymorphic_identity='c') - + @testing.resolve_artifact_names def test_poly_configured_immediate(self): a = A() @@ -250,7 +250,7 @@ class PolymorphicAttributeManagementTest(_base.MappedTest): eq_(a.class_name, 'a') eq_(b.class_name, 'b') eq_(c.class_name, 'c') - + @testing.resolve_artifact_names def test_base_class(self): sess = Session() @@ -273,7 +273,7 @@ class PolymorphicAttributeManagementTest(_base.MappedTest): sess.commit() sess.close() assert isinstance(sess.query(B).first(), C) - + class CascadeTest(_base.MappedTest): """that cascades on polymorphic relationships continue cascading along the path of the instance's mapper, not @@ -378,13 +378,13 @@ class M2OUseGetTest(_base.MappedTest): # the 'primaryjoin' looks just like "Sub"'s "get" clause (based on the Base id), # and foreign_keys since that join condition doesn't actually have any fks in it #'sub':relationship(Sub, primaryjoin=base.c.id==related.c.sub_id, foreign_keys=related.c.sub_id) - + # now we can use this: 'sub':relationship(Sub) }) - + assert class_mapper(Related).get_property('sub').strategy.use_get - + sess = create_session() s1 = Sub() r1 = Related(sub=s1) @@ -397,7 +397,7 @@ class M2OUseGetTest(_base.MappedTest): def go(): assert r1.sub self.assert_sql_count(testing.db, go, 0) - + class GetTest(_base.MappedTest): @classmethod @@ -417,7 +417,7 @@ class GetTest(_base.MappedTest): Column('foo_id', Integer, ForeignKey('foo.id')), Column('bar_id', Integer, ForeignKey('bar.id')), Column('data', String(20))) - + @classmethod def setup_classes(cls): class Foo(_base.BasicEntity): @@ -431,7 +431,7 @@ class GetTest(_base.MappedTest): def test_get_polymorphic(self): self._do_get_test(True) - + def test_get_nonpolymorphic(self): self._do_get_test(False) @@ -469,7 +469,7 @@ class GetTest(_base.MappedTest): assert sess.query(Blub).get(f.id) is None assert sess.query(Blub).get(b.id) is None assert sess.query(Bar).get(f.id) is None - + self.assert_sql_count(testing.db, go, 0) else: # this is testing the 'wrong' behavior of using get() @@ -498,7 +498,7 @@ class GetTest(_base.MappedTest): class EagerLazyTest(_base.MappedTest): """tests eager load/lazy load of child items off inheritance mappers, tests that LazyLoader constructs the right query condition.""" - + @classmethod def define_tables(cls, metadata): global foo, bar, bar_foo @@ -544,7 +544,7 @@ class EagerLazyTest(_base.MappedTest): class EagerTargetingTest(_base.MappedTest): """test a scenario where joined table inheritance might be confused as an eagerly loaded joined table.""" - + @classmethod def define_tables(cls, metadata): Table('a_table', metadata, @@ -558,14 +558,14 @@ class EagerTargetingTest(_base.MappedTest): Column('id', Integer, ForeignKey('a_table.id'), primary_key=True), Column('b_data', String(50)), ) - + @testing.resolve_artifact_names def test_adapt_stringency(self): class A(_base.ComparableEntity): pass class B(A): pass - + mapper(A, a_table, polymorphic_on=a_table.c.type, polymorphic_identity='A', properties={ 'children': relationship(A, order_by=a_table.c.name) @@ -574,7 +574,7 @@ class EagerTargetingTest(_base.MappedTest): mapper(B, b_table, inherits=A, polymorphic_identity='B', properties={ 'b_derived':column_property(b_table.c.b_data + "DATA") }) - + sess=create_session() b1=B(id=1, name='b1',b_data='i') @@ -591,15 +591,15 @@ class EagerTargetingTest(_base.MappedTest): node = sess.query(B).filter(B.id==bid).all()[0] eq_(node, B(id=1, name='b1',b_data='i')) eq_(node.children[0], B(id=2, name='b2',b_data='l')) - + sess.expunge_all() node = sess.query(B).options(joinedload(B.children)).filter(B.id==bid).all()[0] eq_(node, B(id=1, name='b1',b_data='i')) eq_(node.children[0], B(id=2, name='b2',b_data='l')) - + class FlushTest(_base.MappedTest): """test dependency sorting among inheriting mappers""" - + @classmethod def define_tables(cls, metadata): Table('users', metadata, @@ -802,7 +802,7 @@ class VersioningTest(_base.MappedTest): class DistinctPKTest(_base.MappedTest): """test the construction of mapper.primary_key when an inheriting relationship joins on a column other than primary key column.""" - + run_inserts = 'once' run_deletes = None @@ -886,7 +886,7 @@ class DistinctPKTest(_base.MappedTest): class SyncCompileTest(_base.MappedTest): """test that syncrules compile properly on custom inherit conds""" - + @classmethod def define_tables(cls, metadata): global _a_table, _b_table, _c_table @@ -955,17 +955,17 @@ class SyncCompileTest(_base.MappedTest): class OverrideColKeyTest(_base.MappedTest): """test overriding of column attributes.""" - + @classmethod def define_tables(cls, metadata): global base, subtable - + base = Table('base', metadata, Column('base_id', Integer, primary_key=True, test_needs_autoincrement=True), Column('data', String(255)), Column('sqlite_fixer', String(10)) ) - + subtable = Table('subtable', metadata, Column('base_id', Integer, ForeignKey('base.base_id'), primary_key=True), Column('subdata', String(255)) @@ -980,7 +980,7 @@ class OverrideColKeyTest(_base.MappedTest): mapper(Base, base) mapper(Sub, subtable, inherits=Base) - + # Sub gets a "base_id" property using the "base_id" # column of both tables. eq_( @@ -992,12 +992,12 @@ class OverrideColKeyTest(_base.MappedTest): # this pattern is what you see when using declarative # in particular, here we do a "manual" version of # what we'd like the mapper to do. - + class Base(object): pass class Sub(Base): pass - + mapper(Base, base, properties={ 'id':base.c.base_id }) @@ -1018,7 +1018,7 @@ class OverrideColKeyTest(_base.MappedTest): sess.add(s1) sess.flush() assert sess.query(Sub).get(10) is s1 - + def test_override_onlyinparent(self): class Base(object): pass @@ -1029,7 +1029,7 @@ class OverrideColKeyTest(_base.MappedTest): 'id':base.c.base_id }) mapper(Sub, subtable, inherits=Base) - + eq_( class_mapper(Sub).get_property('id').columns, [base.c.base_id] @@ -1039,28 +1039,28 @@ class OverrideColKeyTest(_base.MappedTest): class_mapper(Sub).get_property('base_id').columns, [subtable.c.base_id] ) - + s1 = Sub() s1.id = 10 - + s2 = Sub() s2.base_id = 15 - + sess = create_session() sess.add_all([s1, s2]) sess.flush() - + # s1 gets '10' assert sess.query(Sub).get(10) is s1 - + # s2 gets a new id, base_id is overwritten by the ultimate # PK col assert s2.id == s2.base_id != 15 - + def test_override_implicit(self): # this is originally [ticket:1111]. # the pattern here is now disallowed by [ticket:1892] - + class Base(object): pass class Sub(Base): @@ -1069,7 +1069,7 @@ class OverrideColKeyTest(_base.MappedTest): mapper(Base, base, properties={ 'id':base.c.base_id }) - + def go(): mapper(Sub, subtable, inherits=Base, properties={ 'id':subtable.c.base_id @@ -1082,7 +1082,7 @@ class OverrideColKeyTest(_base.MappedTest): def test_plain_descriptor(self): """test that descriptors prevent inheritance from propigating properties to subclasses.""" - + class Base(object): pass class Sub(Base): @@ -1092,7 +1092,7 @@ class OverrideColKeyTest(_base.MappedTest): mapper(Base, base) mapper(Sub, subtable, inherits=Base) - + s1 = Sub() sess = create_session() sess.add(s1) @@ -1107,7 +1107,7 @@ class OverrideColKeyTest(_base.MappedTest): if instance is None: return self return "im the data" - + class Base(object): pass class Sub(Base): @@ -1121,7 +1121,7 @@ class OverrideColKeyTest(_base.MappedTest): sess.add(s1) sess.flush() assert sess.query(Sub).one().data == "im the data" - + def test_sub_columns_over_base_descriptors(self): class Base(object): @property @@ -1133,7 +1133,7 @@ class OverrideColKeyTest(_base.MappedTest): mapper(Base, base) mapper(Sub, subtable, inherits=Base) - + sess = create_session() b1 = Base() assert b1.subdata == "this is base" @@ -1144,7 +1144,7 @@ class OverrideColKeyTest(_base.MappedTest): sess.add_all([s1, b1]) sess.flush() sess.expunge_all() - + assert sess.query(Base).get(b1.base_id).subdata == "this is base" assert sess.query(Sub).get(s1.base_id).subdata == "this is sub" @@ -1175,7 +1175,7 @@ class OverrideColKeyTest(_base.MappedTest): class OptimizedLoadTest(_base.MappedTest): """tests for the "optimized load" routine.""" - + @classmethod def define_tables(cls, metadata): Table('base', metadata, @@ -1199,19 +1199,19 @@ class OptimizedLoadTest(_base.MappedTest): Column('a', String(10)), Column('b', String(10)) ) - + @testing.resolve_artifact_names def test_optimized_passes(self): """"test that the 'optimized load' routine doesn't crash when a column in the join condition is not available.""" - + class Base(_base.BasicEntity): pass class Sub(Base): pass - + mapper(Base, base, polymorphic_on=base.c.type, polymorphic_identity='base') - + # redefine Sub's "id" to favor the "id" col in the subtable. # "id" is also part of the primary join condition mapper(Sub, sub, inherits=Base, @@ -1222,7 +1222,7 @@ class OptimizedLoadTest(_base.MappedTest): sess.add(s1) sess.commit() sess.expunge_all() - + # load s1 via Base. s1.id won't populate since it's relative to # the "sub" table. The optimized load kicks in and tries to # generate on the primary join, but cannot since "id" is itself unloaded. @@ -1307,7 +1307,7 @@ class OptimizedLoadTest(_base.MappedTest): assert s2test.comp eq_(s1test.comp, Comp('ham', 'cheese')) eq_(s2test.comp, Comp('bacon', 'eggs')) - + @testing.resolve_artifact_names def test_load_expired_on_pending(self): class Base(_base.ComparableEntity): @@ -1343,7 +1343,7 @@ class OptimizedLoadTest(_base.MappedTest): lambda ctx:{u'param_1': s1.id} ), ) - + @testing.resolve_artifact_names def test_dont_generate_on_none(self): class Base(_base.ComparableEntity): @@ -1353,23 +1353,23 @@ class OptimizedLoadTest(_base.MappedTest): mapper(Base, base, polymorphic_on=base.c.type, polymorphic_identity='base') m = mapper(Sub, sub, inherits=Base, polymorphic_identity='sub') - + s1 = Sub() assert m._optimized_get_statement(attributes.instance_state(s1), ['counter2']) is None - + # loads s1.id as None eq_(s1.id, None) - + # this now will come up with a value of None for id - should reject assert m._optimized_get_statement(attributes.instance_state(s1), ['counter2']) is None - + s1.id = 1 attributes.instance_state(s1).commit_all(s1.__dict__, None) assert m._optimized_get_statement(attributes.instance_state(s1), ['counter2']) is not None - + @testing.resolve_artifact_names def test_load_expired_on_pending_twolevel(self): class Base(_base.ComparableEntity): @@ -1378,7 +1378,7 @@ class OptimizedLoadTest(_base.MappedTest): pass class SubSub(Sub): pass - + mapper(Base, base, polymorphic_on=base.c.type, polymorphic_identity='base') mapper(Sub, sub, inherits=Base, polymorphic_identity='sub') @@ -1419,7 +1419,7 @@ class OptimizedLoadTest(_base.MappedTest): lambda ctx:{u'param_1': s1.id} ), ) - + class PKDiscriminatorTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -1427,7 +1427,7 @@ class PKDiscriminatorTest(_base.MappedTest): Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('name', String(60))) - + children = Table('children', metadata, Column('id', Integer, ForeignKey('parents.id'), primary_key=True), @@ -1446,13 +1446,13 @@ class PKDiscriminatorTest(_base.MappedTest): class A(Child): pass - + mapper(Parent, parents, properties={ 'children': relationship(Child, backref='parent'), }) mapper(Child, children, polymorphic_on=children.c.type, polymorphic_identity=1) - + mapper(A, inherits=Child, polymorphic_identity=2) s = create_session() @@ -1464,26 +1464,26 @@ class PKDiscriminatorTest(_base.MappedTest): assert a.id assert a.type == 2 - + p.name='p1new' a.name='a1new' s.flush() - + s.expire_all() assert a.name=='a1new' assert p.name=='p1new' - - + + class DeleteOrphanTest(_base.MappedTest): """Test the fairly obvious, that an error is raised when attempting to insert an orphan. - + Previous SQLA versions would check this constraint in memory which is the original rationale for this test. - + """ - - + + @classmethod def define_tables(cls, metadata): global single, parent @@ -1493,31 +1493,31 @@ class DeleteOrphanTest(_base.MappedTest): Column('data', String(50)), Column('parent_id', Integer, ForeignKey('parent.id'), nullable=False), ) - + parent = Table('parent', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('data', String(50)) ) - + def test_orphan_message(self): class Base(_fixtures.Base): pass - + class SubClass(Base): pass - + class Parent(_fixtures.Base): pass - + mapper(Base, single, polymorphic_on=single.c.type, polymorphic_identity='base') mapper(SubClass, inherits=Base, polymorphic_identity='sub') mapper(Parent, parent, properties={ 'related':relationship(Base, cascade="all, delete-orphan") }) - + sess = create_session() s1 = SubClass(data='s1') sess.add(s1) assert_raises(sa_exc.DBAPIError, sess.flush) - - + + diff --git a/test/orm/inheritance/test_concrete.py b/test/orm/inheritance/test_concrete.py index 9db095d92..4e20e7a78 100644 --- a/test/orm/inheritance/test_concrete.py +++ b/test/orm/inheritance/test_concrete.py @@ -371,7 +371,7 @@ class ConcreteTest(_base.MappedTest): self.assert_sql_count(testing.db, go, 1) - + class PropertyInheritanceTest(_base.MappedTest): @classmethod @@ -389,7 +389,7 @@ class PropertyInheritanceTest(_base.MappedTest): primary_key=True, test_needs_autoincrement=True), Column('some_dest_id', Integer, ForeignKey('dest_table.id')), Column('cname', String(50))) - + Table('dest_table', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('name', String(50))) @@ -402,10 +402,10 @@ class PropertyInheritanceTest(_base.MappedTest): class B(A): pass - + class C(A): pass - + class Dest(_base.ComparableEntity): pass @@ -418,14 +418,14 @@ class PropertyInheritanceTest(_base.MappedTest): dest = Dest() assert_raises(AttributeError, setattr, b, 'some_dest', dest) clear_mappers() - + mapper(A, a_table, properties={'a_id': a_table.c.id}) mapper(B, b_table, inherits=A, concrete=True) mapper(Dest, dest_table) b = B() assert_raises(AttributeError, setattr, b, 'a_id', 3) clear_mappers() - + mapper(A, a_table, properties={'a_id': a_table.c.id}) mapper(B, b_table, inherits=A, concrete=True) mapper(Dest, dest_table) @@ -439,7 +439,7 @@ class PropertyInheritanceTest(_base.MappedTest): properties={ 'some_dest': relationship(Dest, back_populates='many_b') }) - + mapper(Dest, dest_table, properties={ 'many_a': relationship(A,back_populates='some_dest'), 'many_b': relationship(B,back_populates='some_dest') @@ -500,14 +500,14 @@ class PropertyInheritanceTest(_base.MappedTest): properties={ 'some_dest': relationship(Dest, back_populates='many_a')}, ) - + mapper(Dest, dest_table, properties={ 'many_a': relationship(A, back_populates='some_dest', order_by=ajoin.c.id) } ) - + sess = sessionmaker()() dest1 = Dest(name='c1') dest2 = Dest(name='c2') @@ -517,12 +517,12 @@ class PropertyInheritanceTest(_base.MappedTest): b2 = B(some_dest=dest1, bname='b2', id=4) c1 = C(some_dest=dest1, cname='c1', id=5) c2 = C(some_dest=dest2, cname='c2', id=6) - + eq_([a2, c2], dest2.many_a) eq_([a1, b1, b2, c1], dest1.many_a) sess.add_all([dest1, dest2]) sess.commit() - + assert sess.query(Dest).filter(Dest.many_a.contains(a2)).one() is dest2 assert sess.query(Dest).filter(Dest.many_a.contains(b1)).one() is dest1 assert sess.query(Dest).filter(Dest.many_a.contains(c2)).one() is dest2 @@ -576,7 +576,7 @@ class PropertyInheritanceTest(_base.MappedTest): properties={ 'some_dest': relationship(Dest, back_populates='many_a')}, ) - + mapper(Dest, dest_table, properties={ 'many_a': relationship(A, back_populates='some_dest', @@ -596,7 +596,7 @@ class PropertyInheritanceTest(_base.MappedTest): c1 = C(some_dest=dest2, cname='c1') sess.add_all([dest1, dest2, c1, a1, b1]) sess.commit() - + sess2 = sessionmaker()() merged_c1 = sess2.merge(c1) eq_(merged_c1.some_dest.name, 'd2') diff --git a/test/orm/inheritance/test_magazine.py b/test/orm/inheritance/test_magazine.py index e38a1ec33..868bbdcfc 100644 --- a/test/orm/inheritance/test_magazine.py +++ b/test/orm/inheritance/test_magazine.py @@ -198,7 +198,7 @@ def generate_round_trip_test(use_unions=False, use_joins=False): page3 = ClassifiedPage(magazine=magazine,page_no=3) session.add(pub) - + session.flush() print [x for x in session] session.expunge_all() diff --git a/test/orm/inheritance/test_polymorph.py b/test/orm/inheritance/test_polymorph.py index 7e31c476b..9cc58af92 100644 --- a/test/orm/inheritance/test_polymorph.py +++ b/test/orm/inheritance/test_polymorph.py @@ -123,7 +123,7 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, 'engineer':people.join(engineers), 'manager':people.join(managers), }, None, 'pjoin') - + manager_join = people.join(managers).outerjoin(boss) person_with_polymorphic = ['*', person_join] manager_with_polymorphic = ['*', manager_join] @@ -178,11 +178,11 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, Engineer(status='CGG', engineer_name='engineer2', primary_language='python', **{person_attribute_name:'wally'}), Manager(status='ABA', manager_name='manager2', **{person_attribute_name:'jsmith'}) ] - + pointy = employees[0] jsmith = employees[-1] dilbert = employees[1] - + session = create_session() c = Company(name='company1') c.employees = employees @@ -190,7 +190,7 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, session.flush() session.expunge_all() - + eq_(session.query(Person).get(dilbert.person_id), dilbert) session.expunge_all() @@ -200,7 +200,7 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, def go(): cc = session.query(Company).get(c.company_id) eq_(cc.employees, employees) - + if not lazy_relationship: if with_polymorphic != 'none': self.assert_sql_count(testing.db, go, 1) @@ -212,7 +212,7 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, self.assert_sql_count(testing.db, go, 2) else: self.assert_sql_count(testing.db, go, 6) - + # test selecting from the query, using the base mapped table (people) as the selection criterion. # in the case of the polymorphic Person query, the "people" selectable should be adapted to be "person_join" eq_( @@ -226,7 +226,7 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, session.query(Engineer).filter(getattr(Person, person_attribute_name)=='dilbert').first(), dilbert ) - + # test selecting from the query, joining against an alias of the base "people" table. test that # the "palias" alias does *not* get sucked up into the "person_join" conversion. palias = people.alias("palias") @@ -235,12 +235,12 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, assert dilbert is session.query(Engineer).filter((palias.c.name=='dilbert') & (palias.c.person_id==Person.person_id)).first() assert dilbert is session.query(Person).filter((Engineer.engineer_name=="engineer1") & (engineers.c.person_id==people.c.person_id)).first() assert dilbert is session.query(Engineer).filter(Engineer.engineer_name=="engineer1")[0] - + dilbert.engineer_name = 'hes dibert!' session.flush() session.expunge_all() - + def go(): session.query(Person).filter(getattr(Person, person_attribute_name)=='dilbert').first() self.assert_sql_count(testing.db, go, 1) @@ -255,7 +255,7 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, daboss = Boss(status='BBB', manager_name='boss', golf_swing='fore', **{person_attribute_name:'daboss'}) session.add(daboss) assert_raises(sa_exc.DBAPIError, session.flush) - + c = session.query(Company).first() daboss.company = c manager_list = [e for e in c.employees if isinstance(e, Manager)] @@ -264,12 +264,12 @@ def _generate_round_trip_test(include_base, lazy_relationship, redefine_colprop, eq_(session.query(Manager).order_by(Manager.person_id).all(), manager_list) c = session.query(Company).first() - + session.delete(c) session.flush() - + eq_(people.count().scalar(), 0) - + test_roundtrip = function_named( test_roundtrip, "test_%s%s%s_%s" % ( (lazy_relationship and "lazy" or "eager"), diff --git a/test/orm/inheritance/test_polymorph2.py b/test/orm/inheritance/test_polymorph2.py index 2a9341692..92af79ae1 100644 --- a/test/orm/inheritance/test_polymorph2.py +++ b/test/orm/inheritance/test_polymorph2.py @@ -47,9 +47,9 @@ class RelationshipTest1(_base.MappedTest): pass class Manager(Person): pass - + # note that up until recently (0.4.4), we had to specify "foreign_keys" here - # for this primary join. + # for this primary join. mapper(Person, people, properties={ 'manager':relationship(Manager, primaryjoin=(people.c.manager_id == managers.c.person_id), @@ -57,9 +57,9 @@ class RelationshipTest1(_base.MappedTest): }) mapper(Manager, managers, inherits=Person, inherit_condition=people.c.person_id==managers.c.person_id) - + eq_(class_mapper(Person).get_property('manager').synchronize_pairs, [(managers.c.person_id,people.c.manager_id)]) - + session = create_session() p = Person(name='some person') m = Manager(name='some manager') @@ -382,7 +382,7 @@ class RelationshipTest4(_base.MappedTest): session.flush() session.expunge_all() - + def go(): testcar = session.query(Car).options(joinedload('employee')).get(car1.car_id) assert str(testcar.employee) == "Engineer E4, status X" @@ -661,13 +661,13 @@ class RelationshipTest8(_base.MappedTest): sess = create_session() sess.add(t1) sess.flush() - + sess.expunge_all() eq_( sess.query(Taggable).order_by(Taggable.id).all(), [User(data='u1'), Taggable(owner=User(data='u1'))] ) - + class GenerativeTest(TestBase, AssertsExecutionResults): @classmethod def setup_class(cls): @@ -787,7 +787,7 @@ class GenerativeTest(TestBase, AssertsExecutionResults): # added here for testing e = exists([Car.owner], Car.owner==employee_join.c.person_id) Query(Person)._adapt_clause(employee_join, False, False) - + r = session.query(Person).filter(Person.name.like('%2')).join('status').filter_by(name="active").order_by(Person.person_id) eq_(str(list(r)), "[Manager M2, category YYYYYYYYY, status Status active, Engineer E2, field X, status Status active]") r = session.query(Engineer).join('status').filter(Person.name.in_(['E2', 'E3', 'E4', 'M4', 'M2', 'M1']) & (status.c.name=="active")).order_by(Person.name) @@ -1092,7 +1092,7 @@ class MissingPolymorphicOnTest(_base.MappedTest): Column('id', Integer, ForeignKey('tablec.id'), primary_key=True), Column('ddata', String(50)), ) - + def test_polyon_col_setsup(self): class A(_fixtures.Base): pass @@ -1102,16 +1102,16 @@ class MissingPolymorphicOnTest(_base.MappedTest): pass class D(C): pass - + poly_select = select([tablea, tableb.c.data.label('discriminator')], from_obj=tablea.join(tableb)).alias('poly') - + mapper(B, tableb) mapper(A, tablea, with_polymorphic=('*', poly_select), polymorphic_on=poly_select.c.discriminator, properties={ 'b':relationship(B, uselist=False) }) mapper(C, tablec, inherits=A,polymorphic_identity='c') mapper(D, tabled, inherits=C, polymorphic_identity='d') - + c = C(cdata='c1', adata='a1', b=B(data='c')) d = D(cdata='c2', adata='a2', ddata='d2', b=B(data='d')) sess = create_session() @@ -1120,4 +1120,4 @@ class MissingPolymorphicOnTest(_base.MappedTest): sess.flush() sess.expunge_all() eq_(sess.query(A).all(), [C(cdata='c1', adata='a1'), D(cdata='c2', adata='a2', ddata='d2')]) - + diff --git a/test/orm/inheritance/test_query.py b/test/orm/inheritance/test_query.py index 36a23204d..61727eb4e 100644 --- a/test/orm/inheritance/test_query.py +++ b/test/orm/inheritance/test_query.py @@ -25,7 +25,7 @@ class Boss(Manager): class Machine(_fixtures.Base): pass - + class Paperwork(_fixtures.Base): pass @@ -34,7 +34,7 @@ def _produce_test(select_type): run_inserts = 'once' run_setup_mappers = 'once' run_deletes = None - + @classmethod def define_tables(cls, metadata): global companies, people, engineers, managers, boss, paperwork, machines @@ -55,12 +55,12 @@ def _produce_test(select_type): Column('engineer_name', String(50)), Column('primary_language', String(50)), ) - + machines = Table('machines', metadata, Column('machine_id', Integer, primary_key=True, test_needs_autoincrement=True), Column('name', String(50)), Column('engineer_id', Integer, ForeignKey('engineers.person_id'))) - + managers = Table('managers', metadata, Column('person_id', Integer, ForeignKey('people.person_id'), primary_key=True), Column('status', String(30)), @@ -78,7 +78,7 @@ def _produce_test(select_type): Column('person_id', Integer, ForeignKey('people.person_id'))) clear_mappers() - + mapper(Company, companies, properties={ 'employees':relationship(Person, order_by=people.c.person_id) }) @@ -129,7 +129,7 @@ def _produce_test(select_type): inherits=Person, polymorphic_identity='manager') mapper(Boss, boss, inherits=Manager, polymorphic_identity='boss') mapper(Paperwork, paperwork) - + @classmethod def insert_data(cls): @@ -165,7 +165,7 @@ def _produce_test(select_type): Machine(name="Commodore 64"), Machine(name="IBM 3270") ]) - + c2.employees = [e3] sess = create_session() sess.add(c1) @@ -176,10 +176,10 @@ def _produce_test(select_type): all_employees = [e1, e2, b1, m1, e3] c1_employees = [e1, e2, b1, m1] c2_employees = [e3] - + def test_loads_at_once(self): """test that all objects load from the full query, when with_polymorphic is used""" - + sess = create_session() def go(): eq_(sess.query(Person).all(), all_employees) @@ -187,7 +187,7 @@ def _produce_test(select_type): def test_foo(self): sess = create_session() - + def go(): eq_(sess.query(Person).options(subqueryload(Engineer.machines)).all(), all_employees) self.assert_sql_count(testing.db, go, {'':14, 'Unions':8, 'Polymorphic':7}.get(select_type, 8)) @@ -197,13 +197,13 @@ def _produce_test(select_type): # for both joinedload() and subqueryload(), if the original q is not loading # the subclass table, the joinedload doesn't happen. - + def go(): eq_(sess.query(Person).options(joinedload(Engineer.machines))[1:3], all_employees[1:3]) self.assert_sql_count(testing.db, go, {'':6, 'Polymorphic':3}.get(select_type, 4)) sess = create_session() - + def go(): eq_(sess.query(Person).options(subqueryload(Engineer.machines)).all(), all_employees) self.assert_sql_count(testing.db, go, {'':14, 'Unions':8, 'Polymorphic':7}.get(select_type, 8)) @@ -220,26 +220,26 @@ def _produce_test(select_type): options(joinedload(Engineer.machines))[1:3], all_employees[1:3]) self.assert_sql_count(testing.db, go, 3) - - + + def test_get(self): sess = create_session() - + # for all mappers, ensure the primary key has been calculated as just the "person_id" # column eq_(sess.query(Person).get(e1.person_id), Engineer(name="dilbert", primary_language="java")) eq_(sess.query(Engineer).get(e1.person_id), Engineer(name="dilbert", primary_language="java")) eq_(sess.query(Manager).get(b1.person_id), Boss(name="pointy haired boss", golf_swing="fore")) - + def test_multi_join(self): sess = create_session() e = aliased(Person) c = aliased(Company) - + q = sess.query(Company, Person, c, e).join(Person, Company.employees).join(e, c.employees).\ filter(Person.name=='dilbert').filter(e.name=='wally') - + eq_(q.count(), 1) eq_(q.all(), [ ( @@ -249,7 +249,7 @@ def _produce_test(select_type): Engineer(status=u'regular engineer',engineer_name=u'wally',name=u'wally',company_id=1,primary_language=u'c++',person_id=2,type=u'engineer') ) ]) - + def test_filter_on_subclass(self): sess = create_session() eq_(sess.query(Engineer).all()[0], Engineer(name="dilbert")) @@ -261,7 +261,7 @@ def _produce_test(select_type): eq_(sess.query(Manager).filter(Manager.person_id==m1.person_id).one(), Manager(name="dogbert")) eq_(sess.query(Manager).filter(Manager.person_id==b1.person_id).one(), Boss(name="pointy haired boss")) - + eq_(sess.query(Boss).filter(Boss.person_id==b1.person_id).one(), Boss(name="pointy haired boss")) def test_join_from_polymorphic(self): @@ -288,7 +288,7 @@ def _produce_test(select_type): sess.expunge_all() eq_(sess.query(Person).with_polymorphic([Manager, Engineer]).join('paperwork', aliased=aliased).filter(Person.name.like('%dog%')).filter(Paperwork.description.like('%#2%')).all(), [m1]) - + def test_join_to_polymorphic(self): sess = create_session() eq_(sess.query(Company).join('employees').filter(Person.name=='vlad').one(), c2) @@ -302,7 +302,7 @@ def _produce_test(select_type): sess.query(Company).\ filter(Company.employees.any(Person.name=='vlad')).all(), [c2] ) - + # test that the aliasing on "Person" does not bleed into the # EXISTS clause generated by any() eq_( @@ -314,12 +314,12 @@ def _produce_test(select_type): sess.query(Company).join(Company.employees, aliased=True).filter(Person.name=='dilbert').\ filter(Company.employees.any(Person.name=='vlad')).all(), [] ) - + eq_( sess.query(Company).filter(Company.employees.of_type(Engineer).any(Engineer.primary_language=='cobol')).one(), c2 ) - + calias = aliased(Company) eq_( sess.query(calias).filter(calias.employees.of_type(Engineer).any(Engineer.primary_language=='cobol')).one(), @@ -343,12 +343,12 @@ def _produce_test(select_type): eq_( sess.query(Person).filter(Person.paperwork.any(Paperwork.description=="review #2")).all(), [m1] ) - + eq_( sess.query(Company).filter(Company.employees.of_type(Engineer).any(and_(Engineer.primary_language=='cobol'))).one(), c2 ) - + def test_join_from_columns_or_subclass(self): sess = create_session() @@ -356,7 +356,7 @@ def _produce_test(select_type): sess.query(Manager.name).order_by(Manager.name).all(), [(u'dogbert',), (u'pointy haired boss',)] ) - + eq_( sess.query(Manager.name).join(Paperwork, Manager.paperwork).order_by(Manager.name).all(), [(u'dogbert',), (u'dogbert',), (u'pointy haired boss',)] @@ -366,20 +366,20 @@ def _produce_test(select_type): sess.query(Person.name).join(Paperwork, Person.paperwork).order_by(Person.name).all(), [(u'dilbert',), (u'dilbert',), (u'dogbert',), (u'dogbert',), (u'pointy haired boss',), (u'vlad',), (u'wally',), (u'wally',)] ) - + # Load Person.name, joining from Person -> paperwork, get all # the people. eq_( sess.query(Person.name).join(paperwork, Person.person_id==paperwork.c.person_id).order_by(Person.name).all(), [(u'dilbert',), (u'dilbert',), (u'dogbert',), (u'dogbert',), (u'pointy haired boss',), (u'vlad',), (u'wally',), (u'wally',)] ) - + # same, on manager. get only managers. eq_( sess.query(Manager.name).join(paperwork, Manager.person_id==paperwork.c.person_id).order_by(Person.name).all(), [(u'dogbert',), (u'dogbert',), (u'pointy haired boss',)] ) - + if select_type == '': # this now raises, due to [ticket:1892]. Manager.person_id is now the "person_id" column on Manager. # the SQL is incorrect. @@ -400,8 +400,8 @@ def _produce_test(select_type): sess.query(Person.name).join(paperwork, Manager.person_id==paperwork.c.person_id).order_by(Person.name).all(), [(u'dogbert',), (u'dogbert',), (u'pointy haired boss',)] ) - - + + eq_( sess.query(Manager).join(Paperwork, Manager.paperwork).order_by(Manager.name).all(), [m1, b1] @@ -416,7 +416,7 @@ def _produce_test(select_type): sess.query(Manager.person_id).join(paperwork, Manager.person_id==paperwork.c.person_id).order_by(Manager.name).all(), [(4,), (4,), (3,)] ) - + eq_( sess.query(Manager.name, Paperwork.description). join(Paperwork, Manager.person_id==Paperwork.person_id). @@ -424,41 +424,41 @@ def _produce_test(select_type): all(), [(u'pointy haired boss', u'review #1'), (u'dogbert', u'review #2'), (u'dogbert', u'review #3')] ) - + malias = aliased(Manager) eq_( sess.query(malias.name).join(paperwork, malias.person_id==paperwork.c.person_id).all(), [(u'pointy haired boss',), (u'dogbert',), (u'dogbert',)] ) - + def test_polymorphic_option(self): """test that polymorphic loading sets state.load_path with its actual mapper on a subclass, and not the superclass mapper. - + """ paths = [] class MyOption(interfaces.MapperOption): propagate_to_loaders = True def process_query_conditionally(self, query): paths.append(query._current_path) - + sess = create_session() dilbert, boss = sess.query(Person).\ options(MyOption()).\ filter(Person.name.in_(['dilbert', 'pointy haired boss'])).\ order_by(Person.name).\ all() - + dilbert.machines boss.paperwork eq_(paths, [(class_mapper(Engineer), 'machines'), (class_mapper(Boss), 'paperwork')]) - - + + def test_expire(self): """test that individual column refresh doesn't get tripped up by the select_table mapper""" - + sess = create_session() m1 = sess.query(Manager).filter(Manager.name=='dogbert').one() sess.expire(m1) @@ -467,16 +467,16 @@ def _produce_test(select_type): m2 = sess.query(Manager).filter(Manager.name=='pointy haired boss').one() sess.expire(m2, ['manager_name', 'golf_swing']) assert m2.golf_swing=='fore' - + def test_with_polymorphic(self): - + sess = create_session() - - + + assert_raises(sa_exc.InvalidRequestError, sess.query(Person).with_polymorphic, Paperwork) assert_raises(sa_exc.InvalidRequestError, sess.query(Engineer).with_polymorphic, Boss) assert_raises(sa_exc.InvalidRequestError, sess.query(Engineer).with_polymorphic, Person) - + # compare to entities without related collections to prevent additional lazy SQL from firing on # loaded entities emps_without_relationships = [ @@ -487,12 +487,12 @@ def _produce_test(select_type): Engineer(name="vlad", engineer_name="vlad", primary_language="cobol", status="elbonian engineer") ] eq_(sess.query(Person).with_polymorphic('*').all(), emps_without_relationships) - - + + def go(): eq_(sess.query(Person).with_polymorphic(Engineer).filter(Engineer.primary_language=='java').all(), emps_without_relationships[0:1]) self.assert_sql_count(testing.db, go, 1) - + sess.expunge_all() def go(): eq_(sess.query(Person).with_polymorphic('*').all(), emps_without_relationships) @@ -507,13 +507,13 @@ def _produce_test(select_type): def go(): eq_(sess.query(Person).with_polymorphic(Engineer, people.outerjoin(engineers)).all(), emps_without_relationships) self.assert_sql_count(testing.db, go, 3) - + sess.expunge_all() def go(): # limit the polymorphic join down to just "Person", overriding select_table eq_(sess.query(Person).with_polymorphic(Person).all(), emps_without_relationships) self.assert_sql_count(testing.db, go, 6) - + def test_relationship_to_polymorphic(self): assert_result = [ Company(name="MegaCorp, Inc.", employees=[ @@ -528,14 +528,14 @@ def _produce_test(select_type): Engineer(name="vlad", engineer_name="vlad", primary_language="cobol", status="elbonian engineer") ]) ] - + sess = create_session() - + def go(): # test load Companies with lazy load to 'employees' eq_(sess.query(Company).all(), assert_result) self.assert_sql_count(testing.db, go, {'':9, 'Polymorphic':4}.get(select_type, 5)) - + sess = create_session() def go(): # currently, it doesn't matter if we say Company.employees, @@ -546,14 +546,14 @@ def _produce_test(select_type): joinedload_all(Company.employees.of_type(Engineer), Engineer.machines )).all(), assert_result) - + # in the case of select_type='', the joinedload # doesn't take in this case; it joinedloads company->people, - # then a load for each of 5 rows, then lazyload of "machines" + # then a load for each of 5 rows, then lazyload of "machines" self.assert_sql_count(testing.db, go, {'':7, 'Polymorphic':1}.get(select_type, 2) ) - + sess = create_session() def go(): eq_( @@ -561,7 +561,7 @@ def _produce_test(select_type): subqueryload_all(Company.employees.of_type(Engineer), Engineer.machines )).all(), assert_result) - + self.assert_sql_count( testing.db, go, {'':8, @@ -570,7 +570,7 @@ def _produce_test(select_type): 'Polymorphic':3, 'AliasedJoins':4}[select_type] ) - + def test_joinedload_on_subclass(self): sess = create_session() def go(): @@ -588,7 +588,7 @@ def _produce_test(select_type): ) self.assert_sql_count(testing.db, go, 2) - + def test_query_subclass_join_to_base_relationship(self): sess = create_session() # non-polymorphic @@ -601,7 +601,7 @@ def _produce_test(select_type): if select_type == '': eq_(sess.query(Company).select_from(companies.join(people).join(engineers)).filter(Engineer.primary_language=='java').all(), [c1]) eq_(sess.query(Company).join(people.join(engineers), 'employees').filter(Engineer.primary_language=='java').all(), [c1]) - + ealias = aliased(Engineer) eq_(sess.query(Company).join(ealias, 'employees').filter(ealias.primary_language=='java').all(), [c1]) @@ -616,7 +616,7 @@ def _produce_test(select_type): eq_(sess.query(Person).join(Engineer.machines).filter(Machine.name.ilike("%ibm%")).all(), [e1, e3]) eq_(sess.query(Company).join('employees', Engineer.machines).all(), [c1, c2]) eq_(sess.query(Company).join('employees', Engineer.machines).filter(Machine.name.ilike("%thinkpad%")).all(), [c1]) - + # non-polymorphic eq_(sess.query(Engineer).join(Engineer.machines).all(), [e1, e2, e3]) eq_(sess.query(Engineer).join(Engineer.machines).filter(Machine.name.ilike("%ibm%")).all(), [e1, e3]) @@ -647,7 +647,7 @@ def _produce_test(select_type): join('employees', 'paperwork', aliased=aliased).filter(Person.name.in_(['dilbert', 'vlad'])).filter(Paperwork.description.like('%#2%')).all(), [c1] ) - + eq_( sess.query(Company).\ join('employees', 'paperwork', aliased=aliased).filter(Person.name.in_(['dilbert', 'vlad'])).filter(Paperwork.description.like('%#%')).all(), @@ -686,31 +686,31 @@ def _produce_test(select_type): filter(Engineer.engineer_name=='vlad').one(), c2 ) - - + + def test_filter_on_baseclass(self): sess = create_session() eq_(sess.query(Person).all(), all_employees) eq_(sess.query(Person).first(), all_employees[0]) - + eq_(sess.query(Person).filter(Person.person_id==e2.person_id).one(), e2) - + def test_from_alias(self): sess = create_session() - + palias = aliased(Person) eq_( sess.query(palias).filter(palias.name.in_(['dilbert', 'wally'])).all(), [e1, e2] ) - + def test_self_referential(self): sess = create_session() - + c1_employees = [e1, e2, b1, m1] - + palias = aliased(Person) eq_( sess.query(Person, palias).filter(Person.company_id==palias.company_id).filter(Person.name=='dogbert').\ @@ -731,17 +731,17 @@ def _produce_test(select_type): (m1, b1), ] ) - + def test_nesting_queries(self): sess = create_session() - + # query.statement places a flag "no_adapt" on the returned statement. This prevents # the polymorphic adaptation in the second "filter" from hitting it, which would pollute # the subquery and usually results in recursion overflow errors within the adaption. subq = sess.query(engineers.c.person_id).filter(Engineer.primary_language=='java').statement.as_scalar() - + eq_(sess.query(Person).filter(Person.person_id==subq).one(), e1) - + def test_mixed_entities(self): sess = create_session() @@ -756,8 +756,8 @@ def _produce_test(select_type): [(Engineer(status=u'elbonian engineer',engineer_name=u'vlad',name=u'vlad',primary_language=u'cobol'), u'Elbonia, Inc.')] ) - - + + eq_( sess.query(Manager.name).all(), [('pointy haired boss', ), ('dogbert',)] @@ -771,7 +771,7 @@ def _produce_test(select_type): row = sess.query(Engineer.name, Engineer.primary_language).filter(Engineer.name=='dilbert').first() assert row.name == 'dilbert' assert row.primary_language == 'java' - + eq_( sess.query(Engineer.name, Engineer.primary_language).all(), @@ -782,7 +782,7 @@ def _produce_test(select_type): sess.query(Boss.name, Boss.golf_swing).all(), [(u'pointy haired boss', u'fore')] ) - + # TODO: I think raise error on these for now. different inheritance/loading schemes have different # results here, all incorrect # @@ -790,7 +790,7 @@ def _produce_test(select_type): # sess.query(Person.name, Engineer.primary_language).all(), # [] # ) - + # self.assertEquals( # sess.query(Person.name, Engineer.primary_language, Manager.manager_name).all(), # [] @@ -815,7 +815,7 @@ def _produce_test(select_type): (Engineer(status=u'elbonian engineer',engineer_name=u'vlad',name=u'vlad',company_id=2,primary_language=u'cobol',person_id=5,type=u'engineer'), u'Elbonia, Inc.') ] ) - + eq_( sess.query(Engineer.primary_language, Company.name).join(Company.employees).filter(Person.type=='engineer').order_by(desc(Engineer.primary_language)).all(), [(u'java', u'MegaCorp, Inc.'), (u'cobol', u'Elbonia, Inc.'), (u'c++', u'MegaCorp, Inc.')] @@ -841,7 +841,7 @@ def _produce_test(select_type): sess.query(Person.name, Company.name, palias.name).join(Company.employees).filter(Company.name=='Elbonia, Inc.').filter(palias.name=='dilbert').all(), [(u'vlad', u'Elbonia, Inc.', u'dilbert')] ) - + palias = aliased(Person) eq_( sess.query(Person.type, Person.name, palias.type, palias.name).filter(Person.company_id==palias.company_id).filter(Person.name=='dogbert').\ @@ -850,7 +850,7 @@ def _produce_test(select_type): (u'manager', u'dogbert', u'engineer', u'wally'), (u'manager', u'dogbert', u'boss', u'pointy haired boss')] ) - + eq_( sess.query(Person.name, Paperwork.description).filter(Person.person_id==Paperwork.person_id).order_by(Person.name, Paperwork.description).all(), [(u'dilbert', u'tps report #1'), (u'dilbert', u'tps report #2'), (u'dogbert', u'review #2'), @@ -867,7 +867,7 @@ def _produce_test(select_type): sess.query(func.count(Person.person_id)).filter(Engineer.primary_language=='java').all(), [(1, )] ) - + eq_( sess.query(Company.name, func.count(Person.person_id)).filter(Company.company_id==Person.company_id).group_by(Company.name).order_by(Company.name).all(), [(u'Elbonia, Inc.', 1), (u'MegaCorp, Inc.', 4)] @@ -877,20 +877,20 @@ def _produce_test(select_type): sess.query(Company.name, func.count(Person.person_id)).join(Company.employees).group_by(Company.name).order_by(Company.name).all(), [(u'Elbonia, Inc.', 1), (u'MegaCorp, Inc.', 4)] ) - - + + PolymorphicQueryTest.__name__ = "Polymorphic%sTest" % select_type return PolymorphicQueryTest for select_type in ('', 'Polymorphic', 'Unions', 'AliasedJoins', 'Joins'): testclass = _produce_test(select_type) exec("%s = testclass" % testclass.__name__) - + del testclass class SelfReferentialTestJoinedToBase(_base.MappedTest): run_setup_mappers = 'once' - + @classmethod def define_tables(cls, metadata): global people, engineers @@ -913,9 +913,9 @@ class SelfReferentialTestJoinedToBase(_base.MappedTest): polymorphic_identity='engineer', properties={ 'reports_to':relationship(Person, primaryjoin=people.c.person_id==engineers.c.reports_to_id) }) - + def test_has(self): - + p1 = Person(name='dogbert') e1 = Engineer(name='dilbert', primary_language='java', reports_to=p1) sess = create_session() @@ -923,7 +923,7 @@ class SelfReferentialTestJoinedToBase(_base.MappedTest): sess.add(e1) sess.flush() sess.expunge_all() - + eq_(sess.query(Engineer).filter(Engineer.reports_to.has(Person.name=='dogbert')).first(), Engineer(name='dilbert')) def test_oftype_aliases_in_exists(self): @@ -932,9 +932,9 @@ class SelfReferentialTestJoinedToBase(_base.MappedTest): sess = create_session() sess.add_all([e1, e2]) sess.flush() - + eq_(sess.query(Engineer).filter(Engineer.reports_to.of_type(Engineer).has(Engineer.name=='dilbert')).first(), e2) - + def test_join(self): p1 = Person(name='dogbert') e1 = Engineer(name='dilbert', primary_language='java', reports_to=p1) @@ -943,7 +943,7 @@ class SelfReferentialTestJoinedToBase(_base.MappedTest): sess.add(e1) sess.flush() sess.expunge_all() - + eq_( sess.query(Engineer).join('reports_to', aliased=True).filter(Person.name=='dogbert').first(), Engineer(name='dilbert')) @@ -964,7 +964,7 @@ class SelfReferentialJ2JTest(_base.MappedTest): Column('primary_language', String(50)), Column('reports_to_id', Integer, ForeignKey('managers.person_id')) ) - + managers = Table('managers', metadata, Column('person_id', Integer, ForeignKey('people.person_id'), primary_key=True), ) @@ -973,7 +973,7 @@ class SelfReferentialJ2JTest(_base.MappedTest): def setup_mappers(cls): mapper(Person, people, polymorphic_on=people.c.type, polymorphic_identity='person') mapper(Manager, managers, inherits=Person, polymorphic_identity='manager') - + mapper(Engineer, engineers, inherits=Person, polymorphic_identity='engineer', properties={ 'reports_to':relationship(Manager, primaryjoin=managers.c.person_id==engineers.c.reports_to_id, backref='engineers') @@ -1003,7 +1003,7 @@ class SelfReferentialJ2JTest(_base.MappedTest): eq_( sess.query(Engineer).join('reports_to', aliased=True).filter(Manager.name=='dogbert').first(), Engineer(name='dilbert')) - + def test_filter_aliasing(self): m1 = Manager(name='dogbert') m2 = Manager(name='foo') @@ -1033,7 +1033,7 @@ class SelfReferentialJ2JTest(_base.MappedTest): (m1, e1), ] ) - + def test_relationship_compare(self): m1 = Manager(name='dogbert') m2 = Manager(name='foo') @@ -1059,17 +1059,17 @@ class SelfReferentialJ2JTest(_base.MappedTest): [m1] ) - + class M2MFilterTest(_base.MappedTest): run_setup_mappers = 'once' run_inserts = 'once' run_deletes = None - + @classmethod def define_tables(cls, metadata): global people, engineers, organizations, engineers_to_org - + organizations = Table('organizations', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('name', String(50)), @@ -1078,7 +1078,7 @@ class M2MFilterTest(_base.MappedTest): Column('org_id', Integer, ForeignKey('organizations.id')), Column('engineer_id', Integer, ForeignKey('engineers.person_id')), ) - + people = Table('people', metadata, Column('person_id', Integer, primary_key=True, test_needs_autoincrement=True), Column('name', String(50)), @@ -1094,14 +1094,14 @@ class M2MFilterTest(_base.MappedTest): global Organization class Organization(_fixtures.Base): pass - + mapper(Organization, organizations, properties={ 'engineers':relationship(Engineer, secondary=engineers_to_org, backref='organizations') }) - + mapper(Person, people, polymorphic_on=people.c.type, polymorphic_identity='person') mapper(Engineer, engineers, inherits=Person, polymorphic_identity='engineer') - + @classmethod def insert_data(cls): e1 = Engineer(name='e1') @@ -1110,23 +1110,23 @@ class M2MFilterTest(_base.MappedTest): e4 = Engineer(name='e4') org1 = Organization(name='org1', engineers=[e1, e2]) org2 = Organization(name='org2', engineers=[e3, e4]) - + sess = create_session() sess.add(org1) sess.add(org2) sess.flush() - + def test_not_contains(self): sess = create_session() - + e1 = sess.query(Person).filter(Engineer.name=='e1').one() - + # this works eq_(sess.query(Organization).filter(~Organization.engineers.of_type(Engineer).contains(e1)).all(), [Organization(name='org2')]) # this had a bug eq_(sess.query(Organization).filter(~Organization.engineers.contains(e1)).all(), [Organization(name='org2')]) - + def test_any(self): sess = create_session() eq_(sess.query(Organization).filter(Organization.engineers.of_type(Engineer).any(Engineer.name=='e1')).all(), [Organization(name='org1')]) @@ -1134,7 +1134,7 @@ class M2MFilterTest(_base.MappedTest): class SelfReferentialM2MTest(_base.MappedTest, AssertsCompiledSQL): run_setup_mappers = 'once' - + @classmethod def define_tables(cls, metadata): global Parent, Child1, Child2 @@ -1167,19 +1167,19 @@ class SelfReferentialM2MTest(_base.MappedTest, AssertsCompiledSQL): uselist = False, backref="right_children" ) - + def test_query_crit(self): session = create_session() c11, c12, c13 = Child1(), Child1(), Child1() c21, c22, c23 = Child2(), Child2(), Child2() - + c11.left_child2 = c22 c12.left_child2 = c22 c13.left_child2 = c23 - + session.add_all([c11, c12, c13, c21, c22, c23]) session.flush() - + # test that the join to Child2 doesn't alias Child1 in the select eq_( set(session.query(Child1).join(Child1.left_child2)), @@ -1210,12 +1210,12 @@ class SelfReferentialM2MTest(_base.MappedTest, AssertsCompiledSQL): def test_eager_join(self): session = create_session() - + c1 = Child1() c1.left_child2 = Child2() session.add(c1) session.flush() - + q = session.query(Child1).options(joinedload('left_child2')) # test that the splicing of the join works here, doesnt break in the middle of "parent join child1" @@ -1233,21 +1233,21 @@ class SelfReferentialM2MTest(_base.MappedTest, AssertsCompiledSQL): # another way to check assert q.limit(1).with_labels().subquery().count().scalar() == 1 - + assert q.first() is c1 - + def test_subquery_load(self): session = create_session() - + c1 = Child1() c1.left_child2 = Child2() session.add(c1) session.flush() session.expunge_all() - + for row in session.query(Child1).options(subqueryload('left_child2')).all(): assert row.left_child2 - + class EagerToSubclassTest(_base.MappedTest): """Test joinedloads to subclass mappers""" diff --git a/test/orm/inheritance/test_single.py b/test/orm/inheritance/test_single.py index a65851a5f..b5b9dbf88 100644 --- a/test/orm/inheritance/test_single.py +++ b/test/orm/inheritance/test_single.py @@ -43,7 +43,7 @@ class SingleInheritanceTest(testing.AssertsCompiledSQL, MappedTest): mapper(Manager, inherits=Employee, polymorphic_identity='manager') mapper(Engineer, inherits=Employee, polymorphic_identity='engineer') mapper(JuniorEngineer, inherits=Engineer, polymorphic_identity='juniorengineer') - + @testing.resolve_artifact_names def test_single_inheritance(self): @@ -59,7 +59,7 @@ class SingleInheritanceTest(testing.AssertsCompiledSQL, MappedTest): assert session.query(Engineer).all() == [e1, e2] assert session.query(Manager).all() == [m1] assert session.query(JuniorEngineer).all() == [e2] - + m1 = session.query(Manager).one() session.expire(m1, ['manager_data']) eq_(m1.manager_data, "knows how to manage things") @@ -71,11 +71,11 @@ class SingleInheritanceTest(testing.AssertsCompiledSQL, MappedTest): @testing.resolve_artifact_names def test_multi_qualification(self): session = create_session() - + m1 = Manager(name='Tom', manager_data='knows how to manage things') e1 = Engineer(name='Kurt', engineer_info='knows how to hack') e2 = JuniorEngineer(name='Ed', engineer_info='oh that ed') - + session.add_all([m1, e1, e2]) session.flush() @@ -84,7 +84,7 @@ class SingleInheritanceTest(testing.AssertsCompiledSQL, MappedTest): session.query(Manager, ealias).all(), [(m1, e1), (m1, e2)] ) - + eq_( session.query(Manager.name).all(), [("Tom",)] @@ -104,12 +104,12 @@ class SingleInheritanceTest(testing.AssertsCompiledSQL, MappedTest): session.query(Manager).add_entity(ealias).all(), [(m1, e1), (m1, e2)] ) - + eq_( session.query(Manager.name).add_column(ealias.name).all(), [("Tom", "Kurt"), ("Tom", "Ed")] ) - + # TODO: I think raise error on this for now # self.assertEquals( # session.query(Employee.name, Manager.manager_data, Engineer.engineer_info).all(), @@ -140,7 +140,7 @@ class SingleInheritanceTest(testing.AssertsCompiledSQL, MappedTest): 'anon_1 WHERE anon_1.employees_type IN ' '(:type_1, :type_2)', use_default_dialect=True) - + @testing.resolve_artifact_names def test_select_from(self): sess = create_session() @@ -150,12 +150,12 @@ class SingleInheritanceTest(testing.AssertsCompiledSQL, MappedTest): e2 = JuniorEngineer(name='Ed', engineer_info='oh that ed') sess.add_all([m1, m2, e1, e2]) sess.flush() - + eq_( sess.query(Manager).select_from(employees.select().limit(10)).all(), [m1, m2] ) - + @testing.resolve_artifact_names def test_count(self): sess = create_session() @@ -169,7 +169,7 @@ class SingleInheritanceTest(testing.AssertsCompiledSQL, MappedTest): eq_(sess.query(Manager).count(), 2) eq_(sess.query(Engineer).count(), 2) eq_(sess.query(Employee).count(), 4) - + eq_(sess.query(Manager).filter(Manager.name.like('%m%')).count(), 2) eq_(sess.query(Employee).filter(Employee.name.like('%m%')).count(), 3) @@ -216,13 +216,13 @@ class RelationshipFromSingleTest(testing.AssertsCompiledSQL, MappedTest): Column('name', String(50)), Column('type', String(20)), ) - + Table('employee_stuff', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('employee_id', Integer, ForeignKey('employee.id')), Column('name', String(50)), ) - + @classmethod def setup_classes(cls): class Employee(ComparableEntity): @@ -239,7 +239,7 @@ class RelationshipFromSingleTest(testing.AssertsCompiledSQL, MappedTest): 'stuff':relationship(Stuff) }) mapper(Stuff, employee_stuff) - + sess = create_session() context = sess.query(Manager).options(subqueryload('stuff'))._compile_context() subq = context.attributes[('subquery', (class_mapper(Employee), 'stuff'))] @@ -270,17 +270,17 @@ class RelationshipToSingleTest(MappedTest): Column('type', String(20)), Column('company_id', Integer, ForeignKey('companies.company_id')) ) - + Table('companies', metadata, Column('company_id', Integer, primary_key=True, test_needs_autoincrement=True), Column('name', String(50)), ) - + @classmethod def setup_classes(cls): class Company(ComparableEntity): pass - + class Employee(ComparableEntity): pass class Manager(Employee): @@ -300,10 +300,10 @@ class RelationshipToSingleTest(MappedTest): mapper(Engineer, inherits=Employee, polymorphic_identity='engineer') mapper(JuniorEngineer, inherits=Engineer, polymorphic_identity='juniorengineer') sess = sessionmaker()() - + c1 = Company(name='c1') c2 = Company(name='c2') - + m1 = Manager(name='Tom', manager_data='data1', company=c1) m2 = Manager(name='Tom2', manager_data='data2', company=c2) e1 = Engineer(name='Kurt', engineer_info='knows how to hack', company=c2) @@ -338,10 +338,10 @@ class RelationshipToSingleTest(MappedTest): mapper(Engineer, inherits=Employee, polymorphic_identity='engineer') mapper(JuniorEngineer, inherits=Engineer, polymorphic_identity='juniorengineer') sess = sessionmaker()() - + c1 = Company(name='c1') c2 = Company(name='c2') - + m1 = Manager(name='Tom', manager_data='data1', company=c1) m2 = Manager(name='Tom2', manager_data='data2', company=c2) e1 = Engineer(name='Kurt', engineer_info='knows how to hack', company=c2) @@ -351,7 +351,7 @@ class RelationshipToSingleTest(MappedTest): eq_(c1.engineers, [e2]) eq_(c2.engineers, [e1]) - + sess.expunge_all() eq_(sess.query(Company).order_by(Company.name).all(), [ @@ -377,7 +377,7 @@ class RelationshipToSingleTest(MappedTest): (Company(name='c2'), Engineer(name='Kurt')) ] ) - + # join() to Company.engineers, Engineer as the requested entity. # this actually applies the IN criterion twice which is less than ideal. sess.expunge_all() @@ -396,7 +396,7 @@ class RelationshipToSingleTest(MappedTest): ] ) - # this however fails as it does not limit the subtypes to just "Engineer". + # this however fails as it does not limit the subtypes to just "Engineer". # with joins constructed by filter(), we seem to be following a policy where # we don't try to make decisions on how to join to the target class, whereas when using join() we # seem to have a lot more capabilities. @@ -412,12 +412,12 @@ class RelationshipToSingleTest(MappedTest): ] ) go() - + class SingleOnJoinedTest(MappedTest): @classmethod def define_tables(cls, metadata): global persons_table, employees_table - + persons_table = Table('persons', metadata, Column('person_id', Integer, primary_key=True, test_needs_autoincrement=True), Column('name', String(50)), @@ -429,7 +429,7 @@ class SingleOnJoinedTest(MappedTest): Column('employee_data', String(50)), Column('manager_data', String(50)), ) - + def test_single_on_joined(self): class Person(_fixtures.Base): pass @@ -437,18 +437,18 @@ class SingleOnJoinedTest(MappedTest): pass class Manager(Employee): pass - + mapper(Person, persons_table, polymorphic_on=persons_table.c.type, polymorphic_identity='person') mapper(Employee, employees_table, inherits=Person,polymorphic_identity='engineer') mapper(Manager, inherits=Employee,polymorphic_identity='manager') - + sess = create_session() sess.add(Person(name='p1')) sess.add(Employee(name='e1', employee_data='ed1')) sess.add(Manager(name='m1', employee_data='ed2', manager_data='md1')) sess.flush() sess.expunge_all() - + eq_(sess.query(Person).order_by(Person.person_id).all(), [ Person(name='p1'), Employee(name='e1', employee_data='ed1'), @@ -466,7 +466,7 @@ class SingleOnJoinedTest(MappedTest): Manager(name='m1', employee_data='ed2', manager_data='md1') ]) sess.expunge_all() - + def go(): eq_(sess.query(Person).with_polymorphic('*').order_by(Person.person_id).all(), [ Person(name='p1'), @@ -474,4 +474,4 @@ class SingleOnJoinedTest(MappedTest): Manager(name='m1', employee_data='ed2', manager_data='md1') ]) self.assert_sql_count(testing.db, go, 1) - + diff --git a/test/orm/test_assorted_eager.py b/test/orm/test_assorted_eager.py index cedf027dd..eb4104355 100644 --- a/test/orm/test_assorted_eager.py +++ b/test/orm/test_assorted_eager.py @@ -21,15 +21,15 @@ class EagerTest(_base.MappedTest): run_deletes = None run_inserts = "once" run_setup_mappers = "once" - + @classmethod def define_tables(cls, metadata): - + if testing.db.dialect.supports_native_boolean: false = 'false' else: false = "0" - + cls.other_artifacts['false'] = false Table('owners', metadata , @@ -338,7 +338,7 @@ class EagerTest3(_base.MappedTest): arb_result = [row['data_id'] for row in arb_result] arb_data = arb_data.alias('arb') - + # now query for Data objects using that above select, adding the # "order by max desc" separately q = (session.query(Data). diff --git a/test/orm/test_attributes.py b/test/orm/test_attributes.py index e82e9e854..5d74c2062 100644 --- a/test/orm/test_attributes.py +++ b/test/orm/test_attributes.py @@ -122,13 +122,13 @@ class AttributesTest(_base.ORMTest): self.assert_(len(o4.mt2) == 1) self.assert_(o4.mt2[0].a == 'abcde') self.assert_(o4.mt2[0].b is None) - + def test_state_gc(self): """test that InstanceState always has a dict, even after host object gc'ed.""" - + class Foo(object): pass - + instrumentation.register_class(Foo) f = Foo() state = attributes.instance_state(f) @@ -138,7 +138,7 @@ class AttributesTest(_base.ORMTest): gc_collect() assert state.obj() is None assert state.dict == {} - + def test_deferred(self): class Foo(object):pass @@ -233,24 +233,24 @@ class AttributesTest(_base.ORMTest): a.email_address = 'foo@bar.com' u.addresses.append(a) self.assert_(u.user_id == 7 and u.user_name == 'heythere' and u.addresses[0].email_address == 'lala@123.com' and u.addresses[1].email_address == 'foo@bar.com') - + def test_extension_commit_attr(self): """test that an extension which commits attribute history maintains the end-result history. - + This won't work in conjunction with some unitofwork extensions. - + """ - + class Foo(_base.ComparableEntity): pass class Bar(_base.ComparableEntity): pass - + class ReceiveEvents(AttributeExtension): def __init__(self, key): self.key = key - + def append(self, state, child, initiator): if commit: state.commit_all(state.dict) @@ -270,34 +270,34 @@ class AttributesTest(_base.ORMTest): instrumentation.register_class(Bar) b1, b2, b3, b4 = Bar(id='b1'), Bar(id='b2'), Bar(id='b3'), Bar(id='b4') - + def loadcollection(state, passive): if passive is attributes.PASSIVE_NO_FETCH: return attributes.PASSIVE_NO_RESULT return [b1, b2] - + def loadscalar(state, passive): if passive is attributes.PASSIVE_NO_FETCH: return attributes.PASSIVE_NO_RESULT return b2 - + attributes.register_attribute(Foo, 'bars', uselist=True, useobject=True, callable_=loadcollection, extension=[ReceiveEvents('bars')]) - + attributes.register_attribute(Foo, 'bar', uselist=False, useobject=True, callable_=loadscalar, extension=[ReceiveEvents('bar')]) - + attributes.register_attribute(Foo, 'scalar', uselist=False, useobject=False, extension=[ReceiveEvents('scalar')]) - - + + def create_hist(): def hist(key, shouldmatch, fn, *arg): attributes.instance_state(f1).commit_all(attributes.instance_dict(f1)) @@ -314,7 +314,7 @@ class AttributesTest(_base.ORMTest): hist('scalar', True, setattr, f1, 'scalar', 5) hist('scalar', True, setattr, f1, 'scalar', None) hist('scalar', True, setattr, f1, 'scalar', 4) - + histories = [] commit = False create_hist() @@ -330,7 +330,7 @@ class AttributesTest(_base.ORMTest): eq_(woc, wic) else: ne_(woc, wic) - + def test_extension_lazyload_assertion(self): class Foo(_base.BasicEntity): pass @@ -356,7 +356,7 @@ class AttributesTest(_base.ORMTest): def func1(state, passive): if passive is attributes.PASSIVE_NO_FETCH: return attributes.PASSIVE_NO_RESULT - + return [bar1, bar2, bar3] attributes.register_attribute(Foo, 'bars', uselist=True, @@ -367,20 +367,20 @@ class AttributesTest(_base.ORMTest): x = Foo() assert_raises(AssertionError, Bar(id=4).foos.append, x) - + x.bars b = Bar(id=4) b.foos.append(x) attributes.instance_state(x).expire_attributes(attributes.instance_dict(x), ['bars']) assert_raises(AssertionError, b.foos.remove, x) - - + + def test_scalar_listener(self): # listeners on ScalarAttributeImpl and MutableScalarAttributeImpl aren't used normally. # test that they work for the benefit of user extensions class Foo(object): pass - + results = [] class ReceiveEvents(AttributeExtension): def append(self, state, child, initiator): @@ -392,11 +392,11 @@ class AttributesTest(_base.ORMTest): def set(self, state, child, oldchild, initiator): results.append(("set", state.obj(), child, oldchild)) return child - + instrumentation.register_class(Foo) attributes.register_attribute(Foo, 'x', uselist=False, mutable_scalars=False, useobject=False, extension=ReceiveEvents()) attributes.register_attribute(Foo, 'y', uselist=False, mutable_scalars=True, useobject=False, copy_function=lambda x:x, extension=ReceiveEvents()) - + f = Foo() f.x = 5 f.x = 17 @@ -404,7 +404,7 @@ class AttributesTest(_base.ORMTest): f.y = [1,2,3] f.y = [4,5,6] del f.y - + eq_(results, [ ('set', f, 5, None), ('set', f, 17, 5), @@ -413,12 +413,12 @@ class AttributesTest(_base.ORMTest): ('set', f, [4,5,6], [1,2,3]), ('remove', f, [4,5,6]) ]) - - + + def test_lazytrackparent(self): """test that the "hasparent" flag works properly when lazy loaders and backrefs are used - + """ class Post(object):pass @@ -640,7 +640,7 @@ class AttributesTest(_base.ORMTest): attributes.unregister_attribute(Foo, "collection") assert not attributes.manager_of_class(Foo).is_instrumented("collection") - + try: attributes.register_attribute(Foo, "collection", uselist=True, typecallable=dict, useobject=True) assert False @@ -690,11 +690,11 @@ class UtilTest(_base.ORMTest): class Bar(object): pass - + instrumentation.register_class(Foo) instrumentation.register_class(Bar) attributes.register_attribute(Foo, "coll", uselist=True, useobject=True) - + f1 = Foo() b1 = Bar() b2 = Bar() @@ -706,7 +706,7 @@ class UtilTest(_base.ORMTest): eq_(attributes.get_history(f1, "coll"), ([b1], [], [])) attributes.set_committed_value(f1, "coll", [b2]) eq_(attributes.get_history(f1, "coll"), ((), [b2], ())) - + attributes.del_attribute(f1, "coll") assert "coll" not in f1.__dict__ @@ -781,11 +781,11 @@ class BackrefTest(_base.ORMTest): attributes.register_attribute(Port, 'jack', uselist=False, useobject=True, backref="port") - + attributes.register_attribute(Jack, 'port', uselist=False, useobject=True, backref="jack") - - + + p = Port() j = Jack() p.jack = j @@ -800,7 +800,7 @@ class BackrefTest(_base.ORMTest): a token that is global to all InstrumentedAttribute objects within a particular class, not just the indvidual IA object since we use distinct objects in an inheritance scenario. - + """ class Parent(object): pass @@ -811,7 +811,7 @@ class BackrefTest(_base.ORMTest): p_token = object() c_token = object() - + instrumentation.register_class(Parent) instrumentation.register_class(Child) instrumentation.register_class(SubChild) @@ -828,11 +828,11 @@ class BackrefTest(_base.ORMTest): backref="child", parent_token = c_token, useobject=True) - + p1 = Parent() c1 = Child() p1.child = c1 - + c2 = SubChild() c2.parent = p1 @@ -846,7 +846,7 @@ class BackrefTest(_base.ORMTest): p_token = object() c_token = object() - + instrumentation.register_class(Parent) instrumentation.register_class(SubParent) instrumentation.register_class(Child) @@ -862,26 +862,26 @@ class BackrefTest(_base.ORMTest): backref='children', parent_token = c_token, useobject=True) - + p1 = Parent() p2 = SubParent() c1 = Child() - + p1.children.append(c1) assert c1.parent is p1 assert c1 in p1.children - + p2.children.append(c1) assert c1.parent is p2 - + # note its still in p1.children - # the event model currently allows only # one level deep. without the parent_token, # it keeps going until a ValueError is raised # and this condition changes. assert c1 in p1.children - + class PendingBackrefTest(_base.ORMTest): def setup(self): global Post, Blog, called, lazy_load @@ -926,7 +926,7 @@ class PendingBackrefTest(_base.ORMTest): b = Blog("blog 1") p = Post("post 4") - + p.blog = b p = Post("post 5") p.blog = b @@ -936,17 +936,17 @@ class PendingBackrefTest(_base.ORMTest): # calling backref calls the callable, populates extra posts assert b.posts == [p1, p2, p3, Post("post 4"), Post("post 5")] assert called[0] == 1 - + def test_lazy_history(self): global lazy_load p1, p2, p3 = Post("post 1"), Post("post 2"), Post("post 3") lazy_load = [p1, p2, p3] - + b = Blog("blog 1") p = Post("post 4") p.blog = b - + p4 = Post("post 5") p4.blog = b assert called[0] == 0 @@ -1022,7 +1022,7 @@ class HistoryTest(_base.ORMTest): f = Foo() f.someattr = 3 eq_(Foo.someattr.impl.get_committed_value(attributes.instance_state(f), attributes.instance_dict(f)), None) - + attributes.instance_state(f).commit(attributes.instance_dict(f), ['someattr']) eq_(Foo.someattr.impl.get_committed_value(attributes.instance_state(f), attributes.instance_dict(f)), 3) @@ -1084,8 +1084,8 @@ class HistoryTest(_base.ORMTest): eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), (['one'], (), ())) f.someattr = 'two' eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), (['two'], (), ())) - - + + def test_mutable_scalar(self): class Foo(_base.BasicEntity): pass @@ -1138,12 +1138,12 @@ class HistoryTest(_base.ORMTest): attributes.instance_state(f).commit_all(attributes.instance_dict(f)) eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), ((), [{'a':'b'},], ())) - + f.someattr['a'] = 'c' eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), ((), [{'a':'c'},], ())) attributes.flag_modified(f, 'someattr') eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), ([{'a':'c'},], (), ())) - + f.someattr = ['a'] eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), ([['a']], (), ())) attributes.instance_state(f).commit_all(attributes.instance_dict(f)) @@ -1156,7 +1156,7 @@ class HistoryTest(_base.ORMTest): attributes.flag_modified(f, 'someattr') eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), ([['b', 'c']], (), ())) - + def test_use_object(self): class Foo(_base.BasicEntity): pass @@ -1395,10 +1395,10 @@ class HistoryTest(_base.ORMTest): attributes.instance_state(f).commit_all(attributes.instance_dict(f)) eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), ((), [hi, there, hi], ())) - + f.someattr = [] eq_(attributes.get_state_history(attributes.instance_state(f), 'someattr'), ([], [], [hi, there, hi])) - + def test_collections_via_backref(self): class Foo(_base.BasicEntity): pass @@ -1621,12 +1621,12 @@ class HistoryTest(_base.ORMTest): class ListenerTest(_base.ORMTest): def test_receive_changes(self): """test that Listeners can mutate the given value.""" - + class Foo(object): pass class Bar(object): pass - + def append(state, child, initiator): b2 = Bar() b2.data = b1.data + " appended" @@ -1641,11 +1641,11 @@ class ListenerTest(_base.ORMTest): attributes.register_attribute(Foo, 'barlist', uselist=True, useobject=True) attributes.register_attribute(Foo, 'barset', typecallable=set, uselist=True, useobject=True) attributes.register_attribute(Bar, 'data', uselist=False, useobject=False) - + event.listen(Foo.data, 'set', on_set, retval=True) event.listen(Foo.barlist, 'append', append, retval=True) event.listen(Foo.barset, 'append', append, retval=True) - + f1 = Foo() f1.data = "some data" eq_(f1.data, "some data modified") @@ -1654,10 +1654,10 @@ class ListenerTest(_base.ORMTest): f1.barlist.append(b1) assert b1.data == "some bar" assert f1.barlist[0].data == "some bar appended" - + f1.barset.add(b1) assert f1.barset.pop().data == "some bar appended" - + def test_propagate(self): classes = [None, None, None] canary = [] @@ -1665,45 +1665,45 @@ class ListenerTest(_base.ORMTest): class A(object): pass classes[0] = A - + def make_b(): class B(classes[0]): pass classes[1] = B - + def make_c(): class C(classes[1]): pass classes[2] = C - + def instrument_a(): instrumentation.register_class(classes[0]) def instrument_b(): instrumentation.register_class(classes[1]) - + def instrument_c(): instrumentation.register_class(classes[2]) - + def attr_a(): attributes.register_attribute(classes[0], 'attrib', uselist=False, useobject=False) - + def attr_b(): attributes.register_attribute(classes[1], 'attrib', uselist=False, useobject=False) def attr_c(): attributes.register_attribute(classes[2], 'attrib', uselist=False, useobject=False) - + def set(state, value, oldvalue, initiator): canary.append(value) - + def events_a(): event.listen(classes[0].attrib, 'set', set, propagate=True) - + def teardown(): classes[:] = [None, None, None] canary[:] = [] - + ordering = [ (instrument_a, instrument_b), (instrument_b, instrument_c), @@ -1722,20 +1722,20 @@ class ListenerTest(_base.ORMTest): elements = [make_a, make_b, make_c, instrument_a, instrument_b, instrument_c, attr_a, attr_b, attr_c, events_a] - + for i, series in enumerate(all_partial_orderings(ordering, elements)): for fn in series: fn() - + b = classes[1]() b.attrib = "foo" eq_(b.attrib, "foo") eq_(canary, ["foo"]) - + c = classes[2]() c.attrib = "bar" eq_(c.attrib, "bar") eq_(canary, ["foo", "bar"]) - + teardown() - + diff --git a/test/orm/test_backref_mutations.py b/test/orm/test_backref_mutations.py index 455e93a30..d0aae128c 100644 --- a/test/orm/test_backref_mutations.py +++ b/test/orm/test_backref_mutations.py @@ -40,15 +40,15 @@ class O2MCollectionTest(_fixtures.FixtureTest): u2= User(name='ed') sess.add_all([u1, a1, a2, a3]) sess.commit() - + #u1.addresses - + def go(): u2.addresses.append(a1) u2.addresses.append(a2) u2.addresses.append(a3) self.assert_sql_count(testing.db, go, 0) - + @testing.resolve_artifact_names def test_collection_move_preloaded(self): sess = sessionmaker()() @@ -87,7 +87,7 @@ class O2MCollectionTest(_fixtures.FixtureTest): # backref fires assert a1.user is u2 - + # u1.addresses wasn't loaded, # so when it loads its correct assert a1 not in u1.addresses @@ -110,7 +110,7 @@ class O2MCollectionTest(_fixtures.FixtureTest): # backref fires assert a1.user is u2 - + # everything expires, no changes in # u1.addresses, so all is fine sess.commit() @@ -144,7 +144,7 @@ class O2MCollectionTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_plain_load_passive(self): """test that many-to-one set doesn't load the old value.""" - + sess = sessionmaker()() u1 = User(name='jack') u2 = User(name='ed') @@ -159,10 +159,10 @@ class O2MCollectionTest(_fixtures.FixtureTest): def go(): a1.user = u2 self.assert_sql_count(testing.db, go, 0) - + assert a1 not in u1.addresses assert a1 in u2.addresses - + @testing.resolve_artifact_names def test_set_none(self): sess = sessionmaker()() @@ -176,11 +176,11 @@ class O2MCollectionTest(_fixtures.FixtureTest): def go(): a1.user = None self.assert_sql_count(testing.db, go, 0) - + assert a1 not in u1.addresses - - - + + + @testing.resolve_artifact_names def test_scalar_move_notloaded(self): sess = sessionmaker()() @@ -218,7 +218,7 @@ class O2MCollectionTest(_fixtures.FixtureTest): # "old" u1 here allows the backref # to remove it from the addresses collection a1.user = u2 - + sess.commit() assert a1 not in u1.addresses assert a1 in u2.addresses @@ -271,13 +271,13 @@ class O2OScalarBackrefMoveTest(_fixtures.FixtureTest): # load a1.user a1.user - + # reassign a2.user = u1 # backref fires assert u1.address is a2 - + # stays on both sides assert a1.user is u1 assert a2.user is u1 @@ -298,7 +298,7 @@ class O2OScalarBackrefMoveTest(_fixtures.FixtureTest): # backref fires assert a1.user is u2 - + # u1.address loads now after a flush assert u1.address is None assert u2.address is a1 @@ -361,7 +361,7 @@ class O2OScalarBackrefMoveTest(_fixtures.FixtureTest): # load assert a1.user is u1 - + # reassign a2.user = u1 @@ -370,7 +370,7 @@ class O2OScalarBackrefMoveTest(_fixtures.FixtureTest): # didnt work this way tho assert a1.user is u1 - + # moves appropriately after commit sess.commit() assert u1.address is a2 @@ -429,19 +429,19 @@ class O2OScalarOrphanTest(_fixtures.FixtureTest): sess = sessionmaker()() a1 = Address(email_address="address1") u1 = User(name='jack', address=a1) - + sess.add(u1) sess.commit() sess.expunge(u1) - + u2= User(name='ed') # the _SingleParent extension sets the backref get to "active" ! # u1 gets loaded and deleted u2.address = a1 sess.commit() assert sess.query(User).count() == 1 - - + + class M2MScalarMoveTest(_fixtures.FixtureTest): run_inserts = None @@ -452,25 +452,25 @@ class M2MScalarMoveTest(_fixtures.FixtureTest): 'keyword':relationship(Keyword, secondary=item_keywords, uselist=False, backref=backref("item", uselist=False)) }) mapper(Keyword, keywords) - + @testing.resolve_artifact_names def test_collection_move_preloaded(self): sess = sessionmaker()() - + k1 = Keyword(name='k1') i1 = Item(description='i1', keyword=k1) i2 = Item(description='i2') sess.add_all([i1, i2, k1]) sess.commit() # everything is expired - + # load i1.keyword assert i1.keyword is k1 - + i2.keyword = k1 assert k1.item is i2 - + # nothing happens. assert i1.keyword is k1 assert i2.keyword is k1 diff --git a/test/orm/test_cascade.py b/test/orm/test_cascade.py index b36f52ac2..ccc5120f8 100644 --- a/test/orm/test_cascade.py +++ b/test/orm/test_cascade.py @@ -35,7 +35,7 @@ class O2MCascadeDeleteOrphanTest(_base.MappedTest): Column('address_id', Integer, ForeignKey('addresses.id')), Column('data', String(30)) ) - + @classmethod def setup_classes(cls): class User(_base.ComparableEntity): @@ -46,7 +46,7 @@ class O2MCascadeDeleteOrphanTest(_base.MappedTest): pass class Dingaling(_base.ComparableEntity): pass - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): @@ -55,11 +55,11 @@ class O2MCascadeDeleteOrphanTest(_base.MappedTest): mapper(User, users, properties={ 'addresses':relationship(Address, cascade='all, delete-orphan', backref='user'), - + 'orders':relationship(Order, cascade='all, delete-orphan', order_by=orders.c.id) }) - + mapper(Dingaling, dingalings, properties={ 'address' : relationship(Address) }) @@ -122,22 +122,22 @@ class O2MCascadeDeleteOrphanTest(_base.MappedTest): assert o2 in sess assert o3 in sess sess.commit() - + @testing.resolve_artifact_names def test_remove_pending_from_collection(self): sess = Session() - + u = User(name='jack') sess.add(u) sess.commit() - + o1 = Order() u.orders.append(o1) assert o1 in sess u.orders.remove(o1) assert o1 not in sess - - + + @testing.resolve_artifact_names def test_delete(self): sess = create_session() @@ -207,14 +207,14 @@ class O2MCascadeDeleteOrphanTest(_base.MappedTest): def test_cascade_nosideeffects(self): """test that cascade leaves the state of unloaded scalars/collections unchanged.""" - + sess = create_session() u = User(name='jack') sess.add(u) assert 'orders' not in u.__dict__ sess.flush() - + assert 'orders' not in u.__dict__ a = Address(email_address='foo@bar.com') @@ -222,14 +222,14 @@ class O2MCascadeDeleteOrphanTest(_base.MappedTest): assert 'user' not in a.__dict__ a.user = u sess.flush() - + d = Dingaling(data='d1') d.address_id = a.id sess.add(d) assert 'address' not in d.__dict__ sess.flush() assert d.address is a - + @testing.resolve_artifact_names def test_cascade_delete_plusorphans(self): sess = create_session() @@ -268,7 +268,7 @@ class O2MCascadeDeleteOrphanTest(_base.MappedTest): class O2MCascadeDeleteNoOrphanTest(_base.MappedTest): run_inserts = None - + @classmethod def define_tables(cls, metadata): Table('users', metadata, @@ -280,14 +280,14 @@ class O2MCascadeDeleteNoOrphanTest(_base.MappedTest): Column('user_id', Integer, ForeignKey('users.id')), Column('description', String(30)) ) - + @classmethod def setup_classes(cls): class User(_base.ComparableEntity): pass class Order(_base.ComparableEntity): pass - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): @@ -315,7 +315,7 @@ class O2MCascadeDeleteNoOrphanTest(_base.MappedTest): class O2OSingleParentTest(_fixtures.FixtureTest): run_inserts = None - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): @@ -334,12 +334,12 @@ class O2OSingleParentTest(_fixtures.FixtureTest): u1.address = a2 assert u1.address is not a1 assert a1.user is None - + class NoSaveCascadeFlushTest(_fixtures.FixtureTest): """Test related item not present in session, commit proceeds.""" run_inserts = None - + @testing.resolve_artifact_names def _one_to_many_fixture(self, o2m_cascade=True, m2o_cascade=True, @@ -347,7 +347,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): m2o=False, o2m_cascade_backrefs=True, m2o_cascade_backrefs=True): - + if o2m: if m2o: addresses_rel = {'addresses':relationship( @@ -359,7 +359,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): cascade_backrefs=m2o_cascade_backrefs ) )} - + else: addresses_rel = {'addresses':relationship( Address, @@ -376,7 +376,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): else: addresses_rel = {} user_rel = {} - + mapper(User, users, properties=addresses_rel) mapper(Address, addresses, properties=user_rel) @@ -387,7 +387,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): bkd=False, fwd_cascade_backrefs=True, bkd_cascade_backrefs=True): - + if fwd: if bkd: keywords_rel = {'keywords':relationship( @@ -400,7 +400,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): cascade_backrefs=bkd_cascade_backrefs ) )} - + else: keywords_rel = {'keywords':relationship( Keyword, @@ -419,7 +419,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): else: keywords_rel = {} items_rel = {} - + mapper(Item, items, properties=keywords_rel) mapper(Keyword, keywords, properties=items_rel) @@ -434,7 +434,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): assert u1 in sess assert a1 in sess sess.flush() - + @testing.resolve_artifact_names def test_o2m_only_child_transient(self): self._one_to_many_fixture(o2m=True, m2o=False, o2m_cascade=False) @@ -457,9 +457,9 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): a1 = Address(email_address='a1') sess.add(a1) sess.flush() - + sess.expunge_all() - + u1.addresses.append(a1) sess.add(u1) assert u1 in sess @@ -467,7 +467,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): assert_raises_message( sa_exc.SAWarning, "not in session", sess.flush ) - + @testing.resolve_artifact_names def test_o2m_backref_child_pending(self): self._one_to_many_fixture(o2m=True, m2o=True) @@ -511,7 +511,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): sess.commit() go() eq_(u1.addresses, []) - + @testing.resolve_artifact_names def test_o2m_backref_child_expunged(self): self._one_to_many_fixture(o2m=True, m2o=True, @@ -521,7 +521,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): a1 = Address(email_address='a1') sess.add(a1) sess.flush() - + sess.add(u1) u1.addresses.append(a1) sess.expunge(a1) @@ -540,7 +540,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): a1 = Address(email_address='a1') sess.add(a1) sess.flush() - + sess.add(u1) u1.addresses.append(a1) sess.expunge(a1) @@ -585,7 +585,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): u1 = User(name='u1') sess.add(u1) sess.flush() - + a1 = Address(email_address='a1') a1.user = u1 sess.add(a1) @@ -629,7 +629,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): u1 = User(name='u1') sess.add(u1) sess.flush() - + a1 = Address(email_address='a1') a1.user = u1 sess.add(a1) @@ -645,7 +645,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): self._one_to_many_fixture(o2m=True, m2o=True, m2o_cascade=False) sess = Session() u1 = User(name='u1') - + a1 = Address(email_address='a1') a1.user = u1 sess.add(a1) @@ -665,7 +665,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): u1 = User(name='u1') sess.add(u1) sess.flush() - + a1 = Address(email_address='a1') a1.user = u1 sess.add(a1) @@ -690,7 +690,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): assert i1 in sess assert k1 in sess sess.flush() - + @testing.resolve_artifact_names def test_m2m_only_child_transient(self): self._many_to_many_fixture(fwd=True, bkd=False, fwd_cascade=False) @@ -713,9 +713,9 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): k1 = Keyword(name='k1') sess.add(k1) sess.flush() - + sess.expunge_all() - + i1.keywords.append(k1) sess.add(i1) assert i1 in sess @@ -723,7 +723,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): assert_raises_message( sa_exc.SAWarning, "not in session", sess.flush ) - + @testing.resolve_artifact_names def test_m2m_backref_child_pending(self): self._many_to_many_fixture(fwd=True, bkd=True) @@ -767,7 +767,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): sess.commit() go() eq_(i1.keywords, []) - + @testing.resolve_artifact_names def test_m2m_backref_child_expunged(self): self._many_to_many_fixture(fwd=True, bkd=True, @@ -777,7 +777,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): k1 = Keyword(name='k1') sess.add(k1) sess.flush() - + sess.add(i1) i1.keywords.append(k1) sess.expunge(k1) @@ -796,7 +796,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): k1 = Keyword(name='k1') sess.add(k1) sess.flush() - + sess.add(i1) i1.keywords.append(k1) sess.expunge(k1) @@ -811,7 +811,7 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): class NoSaveCascadeBackrefTest(_fixtures.FixtureTest): """test that backrefs don't force save-update cascades to occur when the cascade initiated from the forwards side.""" - + @testing.resolve_artifact_names def test_unidirectional_cascade_o2m(self): mapper(Order, orders) @@ -819,17 +819,17 @@ class NoSaveCascadeBackrefTest(_fixtures.FixtureTest): orders = relationship( Order, backref=backref("user", cascade=None)) )) - + sess = create_session() - + o1 = Order() sess.add(o1) u1 = User(orders=[o1]) assert u1 not in sess assert o1 in sess - + sess.expunge_all() - + o1 = Order() u1 = User(orders=[o1]) sess.add(o1) @@ -842,16 +842,16 @@ class NoSaveCascadeBackrefTest(_fixtures.FixtureTest): 'user':relationship(User, backref=backref("orders", cascade=None)) }) mapper(User, users) - + sess = create_session() - + u1 = User() sess.add(u1) o1 = Order() o1.user = u1 assert o1 not in sess assert u1 in sess - + sess.expunge_all() u1 = User() @@ -876,9 +876,9 @@ class NoSaveCascadeBackrefTest(_fixtures.FixtureTest): i1.keywords.append(k1) assert i1 in sess assert k1 not in sess - + sess.expunge_all() - + i1 = Item() k1 = Keyword() sess.add(i1) @@ -886,7 +886,7 @@ class NoSaveCascadeBackrefTest(_fixtures.FixtureTest): assert i1 in sess assert k1 not in sess - + class M2OCascadeDeleteOrphanTestOne(_base.MappedTest): @classmethod @@ -920,7 +920,7 @@ class M2OCascadeDeleteOrphanTestOne(_base.MappedTest): pass class Foo(_fixtures.Base): pass - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): @@ -960,8 +960,8 @@ class M2OCascadeDeleteOrphanTestOne(_base.MappedTest): """test a bug introduced by r6711""" sess = sessionmaker(expire_on_commit=True)() - - + + u1 = User(name='jack', foo=Foo(data='f1')) sess.add(u1) sess.commit() @@ -975,7 +975,7 @@ class M2OCascadeDeleteOrphanTestOne(_base.MappedTest): attributes.get_history(u1, 'foo'), ([None], (), [attributes.PASSIVE_NO_RESULT]) ) - + sess.add(u1) assert u1 in sess sess.commit() @@ -987,15 +987,15 @@ class M2OCascadeDeleteOrphanTestOne(_base.MappedTest): sess = sessionmaker(expire_on_commit=False)() p1, p2 = Pref(data='p1'), Pref(data='p2') - - + + u = User(name='jack', pref=p1) sess.add(u) sess.commit() sess.close() u.pref = p2 - + sess.add(u) assert p1 in sess assert p2 in sess @@ -1057,13 +1057,13 @@ class M2OCascadeDeleteOrphanTestTwo(_base.MappedTest): test_needs_autoincrement=True), Column('data', String(50)), Column('t2id', Integer, ForeignKey('t2.id'))) - + Table('t2', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('data', String(50)), Column('t3id', Integer, ForeignKey('t3.id'))) - + Table('t3', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), @@ -1146,7 +1146,7 @@ class M2OCascadeDeleteOrphanTestTwo(_base.MappedTest): def test_single_parent_raise(self): sess = create_session() - + y = T2(data='T2a') x = T1(data='T1a', t2=y) assert_raises(sa_exc.InvalidRequestError, T1, data='T1b', t2=y) @@ -1155,13 +1155,13 @@ class M2OCascadeDeleteOrphanTestTwo(_base.MappedTest): def test_single_parent_backref(self): sess = create_session() - + y = T3(data='T3a') x = T2(data='T2a', t3=y) # cant attach the T3 to another T2 assert_raises(sa_exc.InvalidRequestError, T2, data='T2b', t3=y) - + # set via backref tho is OK, unsets from previous parent # first z = T2(data='T2b') @@ -1178,13 +1178,13 @@ class M2OCascadeDeleteNoOrphanTest(_base.MappedTest): test_needs_autoincrement=True), Column('data',String(50)), Column('t2id', Integer, ForeignKey('t2.id'))) - + Table('t2', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('data',String(50)), Column('t3id', Integer, ForeignKey('t3.id'))) - + Table('t3', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), @@ -1310,13 +1310,13 @@ class M2MCascadeTest(_base.MappedTest): test_needs_autoincrement=True), Column('data', String(30)), test_needs_fk=True - + ) Table('atob', metadata, Column('aid', Integer, ForeignKey('a.id')), Column('bid', Integer, ForeignKey('b.id')), test_needs_fk=True - + ) Table('c', metadata, Column('id', Integer, primary_key=True, @@ -1324,7 +1324,7 @@ class M2MCascadeTest(_base.MappedTest): Column('data', String(30)), Column('bid', Integer, ForeignKey('b.id')), test_needs_fk=True - + ) @classmethod @@ -1433,7 +1433,7 @@ class M2MCascadeTest(_base.MappedTest): sess = create_session() b1 =B(data='b1') a1 = A(data='a1', bs=[b1]) - + assert_raises(sa_exc.InvalidRequestError, A, data='a2', bs=[b1] ) @@ -1441,7 +1441,7 @@ class M2MCascadeTest(_base.MappedTest): @testing.resolve_artifact_names def test_single_parent_backref(self): """test that setting m2m via a uselist=False backref bypasses the single_parent raise""" - + mapper(A, a, properties={ 'bs':relationship(B, secondary=atob, @@ -1453,12 +1453,12 @@ class M2MCascadeTest(_base.MappedTest): sess = create_session() b1 =B(data='b1') a1 = A(data='a1', bs=[b1]) - + assert_raises( sa_exc.InvalidRequestError, A, data='a2', bs=[b1] ) - + a2 = A(data='a2') b1.a = a2 assert b1 not in a1.bs @@ -1475,7 +1475,7 @@ class NoBackrefCascadeTest(_fixtures.FixtureTest): 'addresses':relationship(Address, backref='user', cascade_backrefs=False) }) - + mapper(Dingaling, dingalings, properties={ 'address' : relationship(Address, backref='dingalings', cascade_backrefs=False) @@ -1484,10 +1484,10 @@ class NoBackrefCascadeTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_o2m_basic(self): sess = Session() - + u1 = User(name='u1') sess.add(u1) - + a1 = Address(email_address='a1') a1.user = u1 assert a1 not in sess @@ -1496,29 +1496,29 @@ class NoBackrefCascadeTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_o2m_commit_warns(self): sess = Session() - + u1 = User(name='u1') sess.add(u1) - + a1 = Address(email_address='a1') a1.user = u1 - + assert_raises_message( sa_exc.SAWarning, "not in session", sess.commit ) - + assert a1 not in sess - + @testing.resolve_artifact_names def test_o2m_flag_on_backref(self): sess = Session() - + a1 = Address(email_address='a1') sess.add(a1) - + d1 = Dingaling() d1.address = a1 assert d1 in a1.dingalings @@ -1533,7 +1533,7 @@ class NoBackrefCascadeTest(_fixtures.FixtureTest): a1 = Address(email_address='a1') d1 = Dingaling() sess.add(d1) - + a1.dingalings.append(d1) assert a1 not in sess @@ -1543,7 +1543,7 @@ class NoBackrefCascadeTest(_fixtures.FixtureTest): a1 = Address(email_address='a1') sess.add(a1) - + u1 = User(name='u1') u1.addresses.append(a1) assert u1 in sess @@ -1555,7 +1555,7 @@ class NoBackrefCascadeTest(_fixtures.FixtureTest): a1 = Address(email_address='a1') d1 = Dingaling() sess.add(d1) - + a1.dingalings.append(d1) assert a1 not in sess @@ -1592,17 +1592,17 @@ class PendingOrphanTestSingleLevel(_base.MappedTest): pass class Order(_fixtures.Base): pass - + @testing.resolve_artifact_names def test_pending_standalone_orphan(self): """Standalone 'orphan' objects can now be persisted, if the underlying - constraints of the database allow it. - + constraints of the database allow it. + This now supports persisting of objects based on foreign key values alone. - + """ - + mapper(Order, orders) mapper(Address, addresses) mapper(User, users, properties=dict( @@ -1611,13 +1611,13 @@ class PendingOrphanTestSingleLevel(_base.MappedTest): orders=relationship(Order, cascade='all, delete-orphan') )) s = Session() - + # the standalone Address goes in, its foreign key # allows NULL a = Address() s.add(a) s.commit() - + # the standalone Order does not. o = Order() s.add(o) @@ -1633,7 +1633,7 @@ class PendingOrphanTestSingleLevel(_base.MappedTest): s.add(o) s.commit() assert o in s and o not in s.new - + @testing.resolve_artifact_names def test_pending_collection_expunge(self): @@ -1683,11 +1683,11 @@ class PendingOrphanTestSingleLevel(_base.MappedTest): class PendingOrphanTestTwoLevel(_base.MappedTest): """test usages stated at - + http://article.gmane.org/gmane.comp.python.sqlalchemy.user/3085 http://article.gmane.org/gmane.comp.python.sqlalchemy.user/3119 """ - + @classmethod def define_tables(cls, metadata): Table('order', metadata, @@ -1701,7 +1701,7 @@ class PendingOrphanTestTwoLevel(_base.MappedTest): Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('item_id', Integer, ForeignKey('item.id'), nullable=False) ) - + @classmethod def setup_classes(cls): class Order(_base.ComparableEntity): @@ -1710,7 +1710,7 @@ class PendingOrphanTestTwoLevel(_base.MappedTest): pass class Attribute(_base.ComparableEntity): pass - + @testing.resolve_artifact_names def test_singlelevel_remove(self): mapper(Order, order, properties={ @@ -1720,13 +1720,13 @@ class PendingOrphanTestTwoLevel(_base.MappedTest): s = Session() o1 = Order() s.add(o1) - + i1 = Item() o1.items.append(i1) o1.items.remove(i1) s.commit() assert i1 not in o1.items - + @testing.resolve_artifact_names def test_multilevel_remove(self): mapper(Order, order, properties={ @@ -1748,7 +1748,7 @@ class PendingOrphanTestTwoLevel(_base.MappedTest): assert i1 in s assert a1 in s - + # i1 is an orphan so the operation # removes 'i1'. The operation # cascades down to 'a1'. @@ -1756,7 +1756,7 @@ class PendingOrphanTestTwoLevel(_base.MappedTest): assert i1 not in s assert a1 not in s - + s.commit() assert o1 in s assert a1 not in s @@ -1766,7 +1766,7 @@ class PendingOrphanTestTwoLevel(_base.MappedTest): class DoubleParentO2MOrphanTest(_base.MappedTest): """Test orphan behavior on an entity that requires two parents via many-to-one (one-to-many collection.). - + """ @classmethod @@ -1779,7 +1779,7 @@ class DoubleParentO2MOrphanTest(_base.MappedTest): Column('account_id', Integer,primary_key=True, test_needs_autoincrement=True), Column('balance', Integer)) - + Table('customers', meta, Column('customer_id', Integer,primary_key=True, test_needs_autoincrement=True), @@ -1793,7 +1793,7 @@ class DoubleParentO2MOrphanTest(_base.MappedTest): def test_double_parent_expunge_o2m(self): """test the delete-orphan uow event for multiple delete-orphan parent relationships.""" - + class Customer(_fixtures.Base): pass class Account(_fixtures.Base): @@ -1871,11 +1871,11 @@ class DoubleParentO2MOrphanTest(_base.MappedTest): assert c not in s, \ 'Should expunge customer when both parents are gone' - + class DoubleParentM2OOrphanTest(_base.MappedTest): """Test orphan behavior on an entity that requires two parents via one-to-many (many-to-one reference to the orphan). - + """ @classmethod @@ -2013,9 +2013,9 @@ class CollectionAssignmentOrphanTest(_base.MappedTest): class O2MConflictTest(_base.MappedTest): """test that O2M dependency detects a change in parent, does the right thing, and updates the collection/attribute. - + """ - + @classmethod def define_tables(cls, metadata): Table("parent", metadata, @@ -2028,18 +2028,18 @@ class O2MConflictTest(_base.MappedTest): Column('parent_id', Integer, ForeignKey('parent.id'), nullable=False) ) - + @classmethod def setup_classes(cls): class Parent(_base.ComparableEntity): pass class Child(_base.ComparableEntity): pass - + @testing.resolve_artifact_names def _do_move_test(self, delete_old): sess = create_session() - + p1, p2, c1 = Parent(), Parent(), Child() if Parent.child.property.uselist: p1.child.append(c1) @@ -2047,10 +2047,10 @@ class O2MConflictTest(_base.MappedTest): p1.child = c1 sess.add_all([p1, c1]) sess.flush() - + if delete_old: sess.delete(p1) - + if Parent.child.property.uselist: p2.child.append(c1) else: @@ -2086,7 +2086,7 @@ class O2MConflictTest(_base.MappedTest): mapper(Child, child) self._do_move_test(True) self._do_move_test(False) - + @testing.resolve_artifact_names def test_o2o_delcascade_delete_old(self): mapper(Parent, parent, properties={ @@ -2138,7 +2138,7 @@ class O2MConflictTest(_base.MappedTest): }) self._do_move_test(True) self._do_move_test(False) - + class PartialFlushTest(_base.MappedTest): """test cascade behavior as it relates to object lists passed to flush().""" @@ -2218,7 +2218,7 @@ class PartialFlushTest(_base.MappedTest): @testing.resolve_artifact_names def test_circular_sort(self): """test ticket 1306""" - + class Base(_base.ComparableEntity): pass class Parent(Base): @@ -2246,9 +2246,9 @@ class PartialFlushTest(_base.MappedTest): c1, c2, c3 = Child(), Child(), Child() p1.children = [c1, c2, c3] sess.add(p1) - + sess.flush([c1]) assert p1 in sess.new assert c1 not in sess.new assert c2 in sess.new - + diff --git a/test/orm/test_collection.py b/test/orm/test_collection.py index 540213745..8e17b2f2b 100644 --- a/test/orm/test_collection.py +++ b/test/orm/test_collection.py @@ -175,7 +175,7 @@ class CollectionsTest(_base.ORMTest): def invalid(): direct[slice(0, 6, 2)] = [creator()] assert_raises(ValueError, invalid) - + if hasattr(direct, '__delitem__'): e = creator() direct.append(e) @@ -200,7 +200,7 @@ class CollectionsTest(_base.ORMTest): del direct[::2] del control[::2] assert_eq() - + if hasattr(direct, 'remove'): e = creator() direct.append(e) @@ -209,21 +209,21 @@ class CollectionsTest(_base.ORMTest): direct.remove(e) control.remove(e) assert_eq() - + if hasattr(direct, '__setitem__') or hasattr(direct, '__setslice__'): - + values = [creator(), creator()] direct[:] = values control[:] = values assert_eq() - + # test slice assignment where # slice size goes over the number of items values = [creator(), creator()] direct[1:3] = values control[1:3] = values assert_eq() - + values = [creator(), creator()] direct[0:1] = values control[0:1] = values @@ -248,7 +248,7 @@ class CollectionsTest(_base.ORMTest): direct[1::2] = values control[1::2] = values assert_eq() - + values = [creator(), creator()] direct[-1:-3] = values control[-1:-3] = values @@ -258,7 +258,7 @@ class CollectionsTest(_base.ORMTest): direct[-2:-1] = values control[-2:-1] = values assert_eq() - + if hasattr(direct, '__delitem__') or hasattr(direct, '__delslice__'): for i in range(1, 4): @@ -277,7 +277,7 @@ class CollectionsTest(_base.ORMTest): del direct[:] del control[:] assert_eq() - + if hasattr(direct, 'extend'): values = [creator(), creator(), creator()] @@ -377,7 +377,7 @@ class CollectionsTest(_base.ORMTest): self._test_list_bulk(list) def test_list_setitem_with_slices(self): - + # this is a "list" that has no __setslice__ # or __delslice__ methods. The __setitem__ # and __delitem__ must therefore accept @@ -1453,7 +1453,7 @@ class DictHelpersTest(_base.MappedTest): p = session.query(Parent).get(pid) - + eq_(set(p.children.keys()), set(['foo', 'bar'])) cid = p.children['foo'].id @@ -1544,7 +1544,7 @@ class DictHelpersTest(_base.MappedTest): def test_declarative_column_mapped(self): """test that uncompiled attribute usage works with column_mapped_collection""" - + from sqlalchemy.ext.declarative import declarative_base BaseObject = declarative_base() @@ -1553,13 +1553,13 @@ class DictHelpersTest(_base.MappedTest): __tablename__ = "foo" id = Column(Integer(), primary_key=True, test_needs_autoincrement=True) bar_id = Column(Integer, ForeignKey('bar.id')) - + class Bar(BaseObject): __tablename__ = "bar" id = Column(Integer(), primary_key=True, test_needs_autoincrement=True) foos = relationship(Foo, collection_class=collections.column_mapped_collection(Foo.id)) foos2 = relationship(Foo, collection_class=collections.column_mapped_collection((Foo.id, Foo.bar_id))) - + eq_(Bar.foos.property.collection_class().keyfunc(Foo(id=3)), 3) eq_(Bar.foos2.property.collection_class().keyfunc(Foo(id=3, bar_id=12)), (3, 12)) @@ -1574,8 +1574,8 @@ class DictHelpersTest(_base.MappedTest): "for argument 'mapping_spec'; got: 'a'", collections.column_mapped_collection, text('a')) - - + + @testing.resolve_artifact_names def test_column_mapped_collection(self): collection_class = collections.column_mapped_collection( @@ -1760,9 +1760,9 @@ class CustomCollectionsTest(_base.MappedTest): return self.data == other def __repr__(self): return 'ListLike(%s)' % repr(self.data) - + self._test_list(ListLike) - + @testing.resolve_artifact_names def _test_list(self, listcls): class Parent(object): @@ -1801,7 +1801,7 @@ class CustomCollectionsTest(_base.MappedTest): o = [Child()] control[1:3] = o - + p.children[1:3] = o assert control == p.children assert control == list(p.children) diff --git a/test/orm/test_composites.py b/test/orm/test_composites.py index 768d8636e..46d6bb44d 100644 --- a/test/orm/test_composites.py +++ b/test/orm/test_composites.py @@ -61,7 +61,7 @@ class PointTest(_base.MappedTest): 'start':sa.orm.composite(Point, edges.c.x1, edges.c.y1), 'end': sa.orm.composite(Point, edges.c.x2, edges.c.y2) }) - + @testing.resolve_artifact_names def _fixture(self): sess = Session() @@ -72,7 +72,7 @@ class PointTest(_base.MappedTest): sess.add(g) sess.commit() return sess - + @testing.resolve_artifact_names def test_round_trip(self): @@ -80,7 +80,7 @@ class PointTest(_base.MappedTest): g1 = sess.query(Graph).first() sess.close() - + g = sess.query(Graph).get(g1.id) eq_( [(e.start, e.end) for e in g.edges], @@ -88,40 +88,40 @@ class PointTest(_base.MappedTest): (Point(3, 4), Point(5, 6)), (Point(14, 5), Point(2, 7)), ] - ) + ) @testing.resolve_artifact_names def test_detect_change(self): sess = self._fixture() - + g = sess.query(Graph).first() g.edges[1].end = Point(18, 4) sess.commit() e = sess.query(Edge).get(g.edges[1].id) eq_(e.end, Point(18, 4)) - + @testing.resolve_artifact_names def test_eager_load(self): sess = self._fixture() g = sess.query(Graph).first() sess.close() - + def go(): g2 = sess.query(Graph).\ options(sa.orm.joinedload('edges')).\ get(g.id) - + eq_( [(e.start, e.end) for e in g2.edges], [ (Point(3, 4), Point(5, 6)), (Point(14, 5), Point(2, 7)), ] - ) + ) self.assert_sql_count(testing.db, go, 1) - + @testing.resolve_artifact_names def test_comparator(self): sess = self._fixture() @@ -149,12 +149,12 @@ class PointTest(_base.MappedTest): sess.query(Edge.start, Edge.end).all(), [(3, 4, 5, 6), (14, 5, 2, 7)] ) - + @testing.resolve_artifact_names def test_delete(self): sess = self._fixture() g = sess.query(Graph).first() - + e = g.edges[1] del e.end sess.flush() @@ -166,19 +166,19 @@ class PointTest(_base.MappedTest): @testing.resolve_artifact_names def test_save_null(self): """test saving a null composite value - + See google groups thread for more context: http://groups.google.com/group/sqlalchemy/browse_thread/thread/0c6580a1761b2c29 - + """ sess = Session() g = Graph(id=1) e = Edge(None, None) g.edges.append(e) - + sess.add(g) sess.commit() - + g2 = sess.query(Graph).get(1) assert g2.edges[-1].start.x is None assert g2.edges[-1].start.y is None @@ -191,12 +191,12 @@ class PointTest(_base.MappedTest): sess.expire(e) assert 'start' not in e.__dict__ assert e.start == Point(3, 4) - + @testing.resolve_artifact_names def test_default_value(self): e = Edge() eq_(e.start, None) - + class PrimaryKeyTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -205,7 +205,7 @@ class PrimaryKeyTest(_base.MappedTest): test_needs_autoincrement=True), Column('version_id', Integer, primary_key=True, nullable=True), Column('name', String(30))) - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): @@ -229,7 +229,7 @@ class PrimaryKeyTest(_base.MappedTest): mapper(Graph, graphs, properties={ 'version':sa.orm.composite(Version, graphs.c.id, graphs.c.version_id)}) - + @testing.resolve_artifact_names def _fixture(self): @@ -238,13 +238,13 @@ class PrimaryKeyTest(_base.MappedTest): sess.add(g) sess.commit() return sess - + @testing.resolve_artifact_names def test_get_by_col(self): sess = self._fixture() g = sess.query(Graph).first() - + g2 = sess.query(Graph).get([g.id, g.version_id]) eq_(g.version, g2.version) @@ -252,7 +252,7 @@ class PrimaryKeyTest(_base.MappedTest): def test_get_by_composite(self): sess = self._fixture() g = sess.query(Graph).first() - + g2 = sess.query(Graph).get(Version(g.id, g.version_id)) eq_(g.version, g2.version) @@ -272,7 +272,7 @@ class PrimaryKeyTest(_base.MappedTest): @testing.resolve_artifact_names def test_null_pk(self): sess = Session() - + # test pk with one column NULL # only sqlite can really handle this g = Graph(Version(2, None)) @@ -280,7 +280,7 @@ class PrimaryKeyTest(_base.MappedTest): sess.commit() g2 = sess.query(Graph).filter_by(version=Version(2, None)).one() eq_(g.version, g2.version) - + class DefaultsTest(_base.MappedTest): @classmethod @@ -323,7 +323,7 @@ class DefaultsTest(_base.MappedTest): foobars.c.x3, foobars.c.x4) )) - + @testing.resolve_artifact_names def test_attributes_with_defaults(self): @@ -334,12 +334,12 @@ class DefaultsTest(_base.MappedTest): sess.flush() assert f1.foob == FBComposite(2, 5, 15, None) - + f2 = Foobar() sess.add(f2) sess.flush() assert f2.foob == FBComposite(2, None, 15, None) - + @testing.resolve_artifact_names def test_set_composite_values(self): sess = Session() @@ -347,9 +347,9 @@ class DefaultsTest(_base.MappedTest): f1.foob = FBComposite(None, 5, None, None) sess.add(f1) sess.flush() - + assert f1.foob == FBComposite(2, 5, 15, None) - + class MappedSelectTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -367,7 +367,7 @@ class MappedSelectTest(_base.MappedTest): Column('v1', String(20)), Column('v2', String(20)), ) - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): @@ -404,7 +404,7 @@ class MappedSelectTest(_base.MappedTest): desc_values.c.v2), }) - + @testing.resolve_artifact_names def test_set_composite_attrs_via_selectable(self): session = Session() diff --git a/test/orm/test_cycles.py b/test/orm/test_cycles.py index e5e657933..6aa1eaa1a 100644 --- a/test/orm/test_cycles.py +++ b/test/orm/test_cycles.py @@ -65,7 +65,7 @@ class SelfReferentialTest(_base.MappedTest): test that the circular dependency sort can assemble a many-to-one dependency processor when only the object on the "many" side is - actually in the list of modified objects. + actually in the list of modified objects. """ mapper(C1, t1, properties={ @@ -111,7 +111,7 @@ class SelfReferentialTest(_base.MappedTest): mapper(C1, t1, properties={ 'children':relationship(C1) }) - + sess = create_session() c1 = C1() c2 = C1() @@ -119,14 +119,14 @@ class SelfReferentialTest(_base.MappedTest): sess.add(c1) sess.flush() assert c2.parent_c1 == c1.c1 - + sess.delete(c1) sess.flush() assert c2.parent_c1 is None - + sess.expire_all() assert c2.parent_c1 is None - + class SelfReferentialNoPKTest(_base.MappedTest): """A self-referential relationship that joins on a column other than the primary key column""" @@ -300,7 +300,7 @@ class InheritTestTwo(_base.MappedTest): class BiDirectionalManyToOneTest(_base.MappedTest): run_define_tables = 'each' - + @classmethod def define_tables(cls, metadata): Table('t1', metadata, @@ -517,7 +517,7 @@ class OneToManyManyToOneTest(_base.MappedTest): """ run_define_tables = 'each' - + @classmethod def define_tables(cls, metadata): Table('ball', metadata, @@ -618,7 +618,7 @@ class OneToManyManyToOneTest(_base.MappedTest): @testing.resolve_artifact_names def test_post_update_backref(self): """test bidirectional post_update.""" - + mapper(Ball, ball) mapper(Person, person, properties=dict( balls=relationship(Ball, @@ -629,20 +629,20 @@ class OneToManyManyToOneTest(_base.MappedTest): favorite=relationship(Ball, primaryjoin=person.c.favorite_ball_id == ball.c.id, remote_side=person.c.favorite_ball_id) - + )) - + sess = sessionmaker()() p1 = Person(data='p1') p2 = Person(data='p2') p3 = Person(data='p3') - + b1 = Ball(data='b1') - + b1.person = p1 sess.add_all([p1, p2, p3]) sess.commit() - + # switch here. the post_update # on ball.person can't get tripped up # by the fact that there's a "reverse" prop. @@ -658,7 +658,7 @@ class OneToManyManyToOneTest(_base.MappedTest): eq_( p3, b1.person ) - + @testing.resolve_artifact_names @@ -724,9 +724,9 @@ class OneToManyManyToOneTest(_base.MappedTest): ), ) - + sess.delete(p) - + self.assert_sql_execution(testing.db, sess.flush, CompiledSQL("UPDATE ball SET person_id=:person_id " "WHERE ball.id = :ball_id", @@ -750,8 +750,8 @@ class OneToManyManyToOneTest(_base.MappedTest): class SelfReferentialPostUpdateTest(_base.MappedTest): """Post_update on a single self-referential mapper. - - + + """ @classmethod @@ -835,7 +835,7 @@ class SelfReferentialPostUpdateTest(_base.MappedTest): session.flush() remove_child(root, cats) - + # pre-trigger lazy loader on 'cats' to make the test easier cats.children self.assert_sql_execution( @@ -854,7 +854,7 @@ class SelfReferentialPostUpdateTest(_base.MappedTest): "WHERE node.id = :node_id", lambda ctx:{'next_sibling_id':None, 'node_id':cats.id}), ), - + CompiledSQL("DELETE FROM node WHERE node.id = :id", lambda ctx:[{'id':cats.id}]) ) @@ -981,7 +981,7 @@ class SelfReferentialPostUpdateTest3(_base.MappedTest): mapper(Child, child, properties={ 'parent':relationship(Child, remote_side=child.c.id) }) - + session = create_session() p1 = Parent('p1') c1 = Child('c1') @@ -989,7 +989,7 @@ class SelfReferentialPostUpdateTest3(_base.MappedTest): p1.children =[c1, c2] c2.parent = c1 p1.child = c2 - + session.add_all([p1, c1, c2]) session.flush() @@ -998,18 +998,18 @@ class SelfReferentialPostUpdateTest3(_base.MappedTest): p2.children = [c3] p2.child = c3 session.add(p2) - + session.delete(c2) p1.children.remove(c2) p1.child = None session.flush() - + p2.child = None session.flush() - + class PostUpdateBatchingTest(_base.MappedTest): """test that lots of post update cols batch together into a single UPDATE.""" - + @classmethod def define_tables(cls, metadata): Table('parent', metadata, @@ -1037,7 +1037,7 @@ class PostUpdateBatchingTest(_base.MappedTest): Column('name', String(50), nullable=False), Column('parent_id', Integer, ForeignKey('parent.id'), nullable=False)) - + Table('child3', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), @@ -1059,14 +1059,14 @@ class PostUpdateBatchingTest(_base.MappedTest): class Child3(_base.BasicEntity): def __init__(self, name=''): self.name = name - + @testing.resolve_artifact_names def test_one(self): mapper(Parent, parent, properties={ 'c1s':relationship(Child1, primaryjoin=child1.c.parent_id==parent.c.id), 'c2s':relationship(Child2, primaryjoin=child2.c.parent_id==parent.c.id), 'c3s':relationship(Child3, primaryjoin=child3.c.parent_id==parent.c.id), - + 'c1':relationship(Child1, primaryjoin=child1.c.id==parent.c.c1_id, post_update=True), 'c2':relationship(Child2, primaryjoin=child2.c.id==parent.c.c2_id, post_update=True), 'c3':relationship(Child3, primaryjoin=child3.c.id==parent.c.c3_id, post_update=True), @@ -1074,20 +1074,20 @@ class PostUpdateBatchingTest(_base.MappedTest): mapper(Child1, child1) mapper(Child2, child2) mapper(Child3, child3) - + sess = create_session() - + p1 = Parent('p1') c11, c12, c13 = Child1('c1'), Child1('c2'), Child1('c3') c21, c22, c23 = Child2('c1'), Child2('c2'), Child2('c3') c31, c32, c33 = Child3('c1'), Child3('c2'), Child3('c3') - + p1.c1s = [c11, c12, c13] p1.c2s = [c21, c22, c23] p1.c3s = [c31, c32, c33] sess.add(p1) sess.flush() - + p1.c1 = c12 p1.c2 = c23 p1.c3 = c31 @@ -1113,4 +1113,3 @@ class PostUpdateBatchingTest(_base.MappedTest): lambda ctx: {'c2_id': None, 'parent_id': p1.id, 'c1_id': None, 'c3_id': None} ) ) -
\ No newline at end of file diff --git a/test/orm/test_defaults.py b/test/orm/test_defaults.py index f7e39a4fb..004a401c7 100644 --- a/test/orm/test_defaults.py +++ b/test/orm/test_defaults.py @@ -47,7 +47,7 @@ class TriggerDefaultsTest(_base.MappedTest): ), ): event.listen(dt, 'after_create', ins) - + event.listen(dt, 'before_drop', sa.DDL("DROP TRIGGER dt_ins")) for up in ( @@ -128,16 +128,16 @@ class ExcludedDefaultsTest(_base.MappedTest): Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('col1', String(20), default="hello"), ) - + @testing.resolve_artifact_names def test_exclude(self): class Foo(_base.ComparableEntity): pass mapper(Foo, dt, exclude_properties=('col1',)) - + f1 = Foo() sess = create_session() sess.add(f1) sess.flush() eq_(dt.select().execute().fetchall(), [(1, "hello")]) - + diff --git a/test/orm/test_deprecations.py b/test/orm/test_deprecations.py index 2565105a6..400532cb2 100644 --- a/test/orm/test_deprecations.py +++ b/test/orm/test_deprecations.py @@ -97,9 +97,9 @@ class QueryAlternativesTest(_base.MappedTest): @testing.resolve_artifact_names def test_override_get(self): """MapperExtension.get() - + x = session.query.get(5) - + """ from sqlalchemy.orm.query import Query cache = {} @@ -111,25 +111,25 @@ class QueryAlternativesTest(_base.MappedTest): x = super(MyQuery, self).get(ident) cache[ident] = x return x - + session = sessionmaker(query_cls=MyQuery)() - + ad1 = session.query(Address).get(1) assert ad1 in cache.values() - + @testing.resolve_artifact_names def test_load(self): """x = session.query(Address).load(1) - + x = session.load(Address, 1) - + """ session = create_session() ad1 = session.query(Address).populate_existing().get(1) assert bool(ad1) - - + + @testing.resolve_artifact_names def test_apply_max(self): """Query.apply_max(col) diff --git a/test/orm/test_descriptor.py b/test/orm/test_descriptor.py index a09e13047..3ef4afa7f 100644 --- a/test/orm/test_descriptor.py +++ b/test/orm/test_descriptor.py @@ -19,69 +19,69 @@ class TestDescriptor(descriptor_props.DescriptorProperty): self._comparator_factory = partial(comparator_factory, self) else: self._comparator_factory = lambda mapper: None - + class DescriptorInstrumentationTest(_base.ORMTest): def _fixture(self): Base = declarative_base() - + class Foo(Base): __tablename__ = 'foo' id = Column(Integer, primary_key=True) - + return Foo - + def test_fixture(self): Foo = self._fixture() - + d = TestDescriptor(Foo, 'foo') d.instrument_class(Foo.__mapper__) - + assert Foo.foo def test_property_wrapped_classlevel(self): Foo = self._fixture() prop = property(lambda self:None) Foo.foo = prop - + d = TestDescriptor(Foo, 'foo') d.instrument_class(Foo.__mapper__) - + assert Foo().foo is None assert Foo.foo is not prop def test_property_subclass_wrapped_classlevel(self): Foo = self._fixture() - + class myprop(property): attr = 'bar' def method1(self): return "method1" - + def __getitem__(self, key): return 'value' prop = myprop(lambda self:None) Foo.foo = prop - + d = TestDescriptor(Foo, 'foo') d.instrument_class(Foo.__mapper__) - + assert Foo().foo is None assert Foo.foo is not prop assert Foo.foo.attr == 'bar' assert Foo.foo.method1() == 'method1' assert Foo.foo['bar'] == 'value' - + def test_comparator(self): class Comparator(PropComparator): __hash__ = None - + attr = 'bar' - + def method1(self): return "method1" - + def method2(self, other): return "method2" @@ -104,7 +104,7 @@ class DescriptorInstrumentationTest(_base.ORMTest): (Foo.foo == 'bar').__str__(), "foo = upper(:upper_1)" ) - + def test_aliased_comparator(self): class Comparator(ColumnProperty.Comparator): @@ -115,14 +115,14 @@ class DescriptorInstrumentationTest(_base.ORMTest): Foo = self._fixture() Foo._name = Column('name', String) - + def comparator_factory(self, mapper): prop = mapper._props['_name'] return Comparator(prop, mapper) - + d = TestDescriptor(Foo, 'foo', comparator_factory=comparator_factory) d.instrument_class(Foo.__mapper__) - + eq_( str(Foo.foo == 'ed'), "foobar(foo.name) = foobar(:foobar_1)" diff --git a/test/orm/test_dynamic.py b/test/orm/test_dynamic.py index 0958d60dd..ff157407a 100644 --- a/test/orm/test_dynamic.py +++ b/test/orm/test_dynamic.py @@ -20,7 +20,7 @@ class DynamicTest(_fixtures.FixtureTest, AssertsCompiledSQL): q = sess.query(User) u = q.filter(User.id==7).first() - + eq_([User(id=7, addresses=[Address(id=1, email_address='jack@bean.com')])], q.filter(User.id==7).all()) @@ -30,7 +30,7 @@ class DynamicTest(_fixtures.FixtureTest, AssertsCompiledSQL): def test_statement(self): """test that the .statement accessor returns the actual statement that would render, without any _clones called.""" - + mapper(User, users, properties={ 'addresses':dynamic_loader(mapper(Address, addresses)) }) @@ -44,7 +44,7 @@ class DynamicTest(_fixtures.FixtureTest, AssertsCompiledSQL): "addresses WHERE :param_1 = addresses.user_id", use_default_dialect=True ) - + @testing.resolve_artifact_names def test_order_by(self): mapper(User, users, properties={ @@ -133,7 +133,7 @@ class DynamicTest(_fixtures.FixtureTest, AssertsCompiledSQL): "Dynamic attributes don't support collection population.", attributes.set_committed_value, u1, 'addresses', [] ) - + @testing.resolve_artifact_names def test_m2m(self): mapper(Order, orders, properties={ @@ -178,8 +178,8 @@ class DynamicTest(_fixtures.FixtureTest, AssertsCompiledSQL): o.items.filter(order_items.c.item_id==2).all(), [Item(id=2)] ) - - + + @testing.resolve_artifact_names def test_transient_detached(self): mapper(User, users, properties={ diff --git a/test/orm/test_eager_relations.py b/test/orm/test_eager_relations.py index e3d14fede..095254b27 100644 --- a/test/orm/test_eager_relations.py +++ b/test/orm/test_eager_relations.py @@ -39,7 +39,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): sess = create_session() sess.query(User).all() m.add_property("addresses", relationship(mapper(Address, addresses))) - + sess.expunge_all() def go(): eq_( @@ -47,12 +47,12 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): sess.query(User).options(joinedload('addresses')).filter(User.id==7).all() ) self.assert_sql_count(testing.db, go, 1) - - + + @testing.resolve_artifact_names def test_no_orphan(self): """An eagerly loaded child object is not marked as an orphan""" - + mapper(User, users, properties={ 'addresses':relationship(Address, cascade="all,delete-orphan", lazy='joined') }) @@ -114,7 +114,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): def test_orderby_related(self): """A regular mapper select on a single table can order by a relationship to a second table""" - + mapper(Address, addresses) mapper(User, users, properties = dict( addresses = relationship(Address, lazy='joined', order_by=addresses.c.id), @@ -290,7 +290,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): @testing.resolve_artifact_names def test_disable_dynamic(self): """test no joined option on a dynamic.""" - + mapper(User, users, properties={ 'addresses':relationship(Address, lazy="dynamic") }) @@ -368,10 +368,10 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): mapper(Address, addresses) mapper(Order, orders) - + open_mapper = mapper(Order, openorders, non_primary=True) closed_mapper = mapper(Order, closedorders, non_primary=True) - + mapper(User, users, properties = dict( addresses = relationship(Address, lazy='joined', order_by=addresses.c.id), open_orders = relationship( @@ -628,12 +628,12 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): def test_useget_cancels_eager(self): """test that a one to many lazyload cancels the unnecessary eager many-to-one join on the other side.""" - + mapper(User, users) mapper(Address, addresses, properties={ 'user':relationship(User, lazy='joined', backref='addresses') }) - + sess = create_session() u1 = sess.query(User).filter(User.id==8).one() def go(): @@ -646,13 +646,13 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): "addresses.user_id", {'param_1': 8}) ) - - + + @testing.resolve_artifact_names def test_manytoone_limit(self): """test that the subquery wrapping only occurs with limit/offset and m2m or o2m joins present.""" - + mapper(User, users, properties=odict( orders=relationship(Order, backref='user') )) @@ -662,7 +662,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): )) mapper(Address, addresses) mapper(Item, items) - + sess = create_session() self.assert_compile( @@ -740,7 +740,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): {'param_1':10}, use_default_dialect=True ) - + self.assert_compile( sess.query(User).options(joinedload("orders", innerjoin=True), joinedload("orders.address", innerjoin=True)).limit(10), @@ -756,7 +756,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): {'param_1':10}, use_default_dialect=True ) - + @testing.resolve_artifact_names def test_one_to_many_scalar(self): mapper(User, users, properties = dict( @@ -790,9 +790,9 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): def test_many_to_one_null(self): """test that a many-to-one eager load which loads None does not later trigger a lazy load. - + """ - + # use a primaryjoin intended to defeat SA's usage of # query.get() for a many-to-one lazyload mapper(Order, orders, properties = dict( @@ -801,7 +801,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): addresses.c.id==orders.c.address_id, addresses.c.email_address != None ), - + lazy='joined') )) sess = create_session() @@ -810,13 +810,13 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): o1 = sess.query(Order).options(lazyload('address')).filter(Order.id==5).one() eq_(o1.address, None) self.assert_sql_count(testing.db, go, 2) - + sess.expunge_all() def go(): o1 = sess.query(Order).filter(Order.id==5).one() eq_(o1.address, None) self.assert_sql_count(testing.db, go, 1) - + @testing.resolve_artifact_names def test_one_and_many(self): """tests eager load for a parent object with a child object that @@ -879,7 +879,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): def test_uselist_false_warning(self): """test that multiple rows received by a uselist=False raises a warning.""" - + mapper(User, users, properties={ 'order':relationship(Order, uselist=False) }) @@ -887,7 +887,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): s = create_session() assert_raises(sa.exc.SAWarning, s.query(User).options(joinedload(User.order)).all) - + @testing.resolve_artifact_names def test_wide(self): mapper(Order, orders, properties={'items':relationship(Item, secondary=order_items, lazy='joined', @@ -972,7 +972,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): innerjoin=True) )) mapper(Item, items) - + sess = create_session() self.assert_compile( sess.query(User), @@ -986,7 +986,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): "order_items_1.item_id", use_default_dialect=True ) - + self.assert_compile( sess.query(User).options(joinedload(User.orders, innerjoin=False)), "SELECT users.id AS users_id, users.name AS users_name, items_1.id AS " @@ -1012,7 +1012,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): "order_items_1.item_id", use_default_dialect=True ) - + @testing.resolve_artifact_names def test_inner_join_chaining_fixed(self): mapper(User, users, properties = dict( @@ -1023,7 +1023,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): innerjoin=True) )) mapper(Item, items) - + sess = create_session() # joining from user, its all LEFT OUTER JOINs @@ -1039,7 +1039,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): "order_items_1.item_id", use_default_dialect=True ) - + # joining just from Order, innerjoin=True can be respected self.assert_compile( sess.query(Order), @@ -1052,8 +1052,8 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): "order_items_1.item_id", use_default_dialect=True ) - - + + @testing.resolve_artifact_names def test_inner_join_options(self): @@ -1081,14 +1081,14 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): "order_items_1 ON orders_1.id = order_items_1.order_id JOIN items AS items_1 ON " "items_1.id = order_items_1.item_id ORDER BY orders_1.id, items_1.id" , use_default_dialect=True) - + def go(): eq_( sess.query(User).options( joinedload(User.orders, innerjoin=True), joinedload(User.orders, Order.items, innerjoin=True)). order_by(User.id).all(), - + [User(id=7, orders=[ Order(id=1, items=[ Item(id=1), Item(id=2), Item(id=3)]), @@ -1100,7 +1100,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): ] ) self.assert_sql_count(testing.db, go, 1) - + # test that default innerjoin setting is used for options self.assert_compile( sess.query(Order).options(joinedload(Order.user)).filter(Order.description == 'foo'), @@ -1111,7 +1111,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): "WHERE orders.description = :description_1", use_default_dialect=True ) - + class AddEntityTest(_fixtures.FixtureTest): run_inserts = 'once' run_deletes = None @@ -1511,7 +1511,7 @@ class MixedSelfReferentialEagerTest(_base.MappedTest): pass class B(_base.ComparableEntity): pass - + mapper(A,a_table) mapper(B,b_table,properties = { 'parent_b1': relationship(B, @@ -1526,7 +1526,7 @@ class MixedSelfReferentialEagerTest(_base.MappedTest): order_by = b_table.c.id ) }); - + @classmethod @testing.resolve_artifact_names def insert_data(cls): @@ -1547,7 +1547,7 @@ class MixedSelfReferentialEagerTest(_base.MappedTest): dict(id=13, parent_a_id=3, parent_b1_id=4, parent_b2_id=4), dict(id=14, parent_a_id=3, parent_b1_id=7, parent_b2_id=2), ) - + @testing.resolve_artifact_names def test_eager_load(self): session = create_session() @@ -1566,7 +1566,7 @@ class MixedSelfReferentialEagerTest(_base.MappedTest): ] ) self.assert_sql_count(testing.db, go, 1) - + class SelfReferentialM2MEagerTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -1659,7 +1659,7 @@ class MixedEntitiesTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): @testing.resolve_artifact_names def test_two_entities_with_joins(self): sess = create_session() - + # two FROM clauses where there's a join on each one def go(): u1 = aliased(User) @@ -1694,8 +1694,8 @@ class MixedEntitiesTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): order_by(User.id, Order.id, u1.id, o1.id).all(), ) self.assert_sql_count(testing.db, go, 1) - - + + @testing.resolve_artifact_names def test_aliased_entity(self): @@ -1871,18 +1871,18 @@ class SubqueryTest(_base.MappedTest): class CorrelatedSubqueryTest(_base.MappedTest): """tests for #946, #947, #948. - + The "users" table is joined to "stuff", and the relationship would like to pull only the "stuff" entry with the most recent date. - + Exercises a variety of ways to configure this. - + """ # another argument for joinedload learning about inner joins - + __requires__ = ('correlated_outer_joins', ) - + @classmethod def define_tables(cls, metadata): users = Table('users', metadata, @@ -1894,7 +1894,7 @@ class CorrelatedSubqueryTest(_base.MappedTest): Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('date', Date), Column('user_id', Integer, ForeignKey('users.id'))) - + @classmethod @testing.resolve_artifact_names def insert_data(cls): @@ -1912,8 +1912,8 @@ class CorrelatedSubqueryTest(_base.MappedTest): {'id':5, 'user_id':3, 'date':datetime.date(2007, 6, 15)}, {'id':6, 'user_id':3, 'date':datetime.date(2007, 3, 15)}, ) - - + + def test_labeled_on_date_noalias(self): self._do_test('label', True, False) @@ -1949,7 +1949,7 @@ class CorrelatedSubqueryTest(_base.MappedTest): def test_plain_on_limitid_alias(self): self._do_test('none', False, True) - + @testing.resolve_artifact_names def _do_test(self, labeled, ondate, aliasstuff): class User(_base.ComparableEntity): @@ -1957,7 +1957,7 @@ class CorrelatedSubqueryTest(_base.MappedTest): class Stuff(_base.ComparableEntity): pass - + mapper(Stuff, stuff) if aliasstuff: @@ -1991,7 +1991,7 @@ class CorrelatedSubqueryTest(_base.MappedTest): mapper(User, users, properties={ 'stuff':relationship(Stuff, primaryjoin=and_(users.c.id==stuff.c.user_id, stuff.c.id==stuff_view)) }) - + sess = create_session() def go(): eq_( @@ -2003,7 +2003,7 @@ class CorrelatedSubqueryTest(_base.MappedTest): ] ) self.assert_sql_count(testing.db, go, 1) - + sess = create_session() def go(): eq_( diff --git a/test/orm/test_evaluator.py b/test/orm/test_evaluator.py index 26f9f49c3..017619cfe 100644 --- a/test/orm/test_evaluator.py +++ b/test/orm/test_evaluator.py @@ -27,17 +27,17 @@ class EvaluateTest(_base.MappedTest): Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String(64))) - + @classmethod def setup_classes(cls): class User(_base.ComparableEntity): pass - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): mapper(User, users) - + @testing.resolve_artifact_names def test_compare_to_value(self): eval_eq(User.name == 'foo', testcases=[ @@ -45,20 +45,20 @@ class EvaluateTest(_base.MappedTest): (User(name='bar'), False), (User(name=None), None), ]) - + eval_eq(User.id < 5, testcases=[ (User(id=3), True), (User(id=5), False), (User(id=None), None), ]) - + @testing.resolve_artifact_names def test_compare_to_none(self): eval_eq(User.name == None, testcases=[ (User(name='foo'), False), (User(name=None), True), ]) - + @testing.resolve_artifact_names def test_boolean_ops(self): eval_eq(and_(User.name == 'foo', User.id == 1), testcases=[ @@ -68,7 +68,7 @@ class EvaluateTest(_base.MappedTest): (User(id=2, name='bar'), False), (User(id=1, name=None), None), ]) - + eval_eq(or_(User.name == 'foo', User.id == 1), testcases=[ (User(id=1, name='foo'), True), (User(id=2, name='foo'), True), @@ -77,7 +77,7 @@ class EvaluateTest(_base.MappedTest): (User(id=1, name=None), True), (User(id=2, name=None), None), ]) - + eval_eq(not_(User.id == 1), testcases=[ (User(id=1), False), (User(id=2), True), diff --git a/test/orm/test_events.py b/test/orm/test_events.py index b2900c93f..25f94e487 100644 --- a/test/orm/test_events.py +++ b/test/orm/test_events.py @@ -21,27 +21,27 @@ class _RemoveListeners(object): ClassManager.dispatch._clear() Session.dispatch._clear() super(_RemoveListeners, self).teardown() - + class MapperEventsTest(_RemoveListeners, _fixtures.FixtureTest): run_inserts = None - + @testing.resolve_artifact_names def test_instance_event_listen(self): """test listen targets for instance events""" - + canary = [] class A(object): pass class B(A): pass - + mapper(A, users) mapper(B, addresses, inherits=A) - + def init_a(target, args, kwargs): canary.append(('init_a', target)) - + def init_b(target, args, kwargs): canary.append(('init_b', target)) @@ -53,30 +53,30 @@ class MapperEventsTest(_RemoveListeners, _fixtures.FixtureTest): def init_e(target, args, kwargs): canary.append(('init_e', target)) - + event.listen(mapper, 'init', init_a) event.listen(Mapper, 'init', init_b) event.listen(class_mapper(A), 'init', init_c) event.listen(A, 'init', init_d) event.listen(A, 'init', init_e, propagate=True) - + a = A() eq_(canary, [('init_a', a),('init_b', a), ('init_c', a),('init_d', a),('init_e', a)]) - + # test propagate flag canary[:] = [] b = B() eq_(canary, [('init_a', b), ('init_b', b),('init_e', b)]) - - + + def listen_all(self, mapper, **kw): canary = [] def evt(meth): def go(*args, **kwargs): canary.append(meth) return go - + for meth in [ 'init', 'init_failure', @@ -102,7 +102,7 @@ class MapperEventsTest(_RemoveListeners, _fixtures.FixtureTest): mapper(User, users) canary = self.listen_all(User) - + sess = create_session() u = User(name='u1') sess.add(u) @@ -164,16 +164,16 @@ class MapperEventsTest(_RemoveListeners, _fixtures.FixtureTest): def test_before_after_only_collection(self): """before_update is called on parent for collection modifications, after_update is called even if no columns were updated. - + """ mapper(Item, items, properties={ 'keywords': relationship(Keyword, secondary=item_keywords)}) mapper(Keyword, keywords) - + canary1 = self.listen_all(Item) canary2 = self.listen_all(Keyword) - + sess = create_session() i1 = Item(description="i1") k1 = Keyword(name="k1") @@ -195,14 +195,14 @@ class MapperEventsTest(_RemoveListeners, _fixtures.FixtureTest): eq_(canary1, ['before_update', 'after_update']) eq_(canary2, []) - + @testing.resolve_artifact_names def test_retval(self): def create_instance(mapper, context, row, class_): u = User.__new__(User) u.foo = True return u - + mapper(User, users) event.listen(User, 'create_instance', create_instance, retval=True) sess = create_session() @@ -213,20 +213,20 @@ class MapperEventsTest(_RemoveListeners, _fixtures.FixtureTest): sess.expunge_all() u = sess.query(User).first() assert u.foo - + @testing.resolve_artifact_names def test_instrument_event(self): canary = [] def instrument_class(mapper, cls): canary.append(cls) - + event.listen(Mapper, 'instrument_class', instrument_class) - + mapper(User, users) eq_(canary, [User]) mapper(Address, addresses) eq_(canary, [User, Address]) - + class LoadTest(_fixtures.FixtureTest): run_inserts = None @@ -235,7 +235,7 @@ class LoadTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def setup_mappers(cls): mapper(User, users) - + @testing.resolve_artifact_names def _fixture(self): canary = [] @@ -243,7 +243,7 @@ class LoadTest(_fixtures.FixtureTest): canary.append("load") def refresh(target, ctx, attrs): canary.append(("refresh", attrs)) - + event.listen(User, "load", load) event.listen(User, "refresh", refresh) return canary @@ -251,33 +251,33 @@ class LoadTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_just_loaded(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.commit() sess.close() - + sess.query(User).first() eq_(canary, ['load']) @testing.resolve_artifact_names def test_repeated_rows(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.commit() sess.close() - + sess.query(User).union_all(sess.query(User)).all() eq_(canary, ['load']) - - - + + + class RefreshTest(_fixtures.FixtureTest): run_inserts = None @@ -285,7 +285,7 @@ class RefreshTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def setup_mappers(cls): mapper(User, users) - + @testing.resolve_artifact_names def _fixture(self): canary = [] @@ -293,7 +293,7 @@ class RefreshTest(_fixtures.FixtureTest): canary.append("load") def refresh(target, ctx, attrs): canary.append(("refresh", attrs)) - + event.listen(User, "load", load) event.listen(User, "refresh", refresh) return canary @@ -301,96 +301,96 @@ class RefreshTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_already_present(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.flush() - + sess.query(User).first() eq_(canary, []) @testing.resolve_artifact_names def test_repeated_rows(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.commit() - + sess.query(User).union_all(sess.query(User)).all() eq_(canary, [('refresh', set(['id','name']))]) @testing.resolve_artifact_names def test_via_refresh_state(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.commit() - + u1.name eq_(canary, [('refresh', set(['id','name']))]) @testing.resolve_artifact_names def test_was_expired(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.flush() sess.expire(u1) - + sess.query(User).first() eq_(canary, [('refresh', set(['id','name']))]) @testing.resolve_artifact_names def test_was_expired_via_commit(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.commit() - + sess.query(User).first() eq_(canary, [('refresh', set(['id','name']))]) @testing.resolve_artifact_names def test_was_expired_attrs(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.flush() sess.expire(u1, ['name']) - + sess.query(User).first() eq_(canary, [('refresh', set(['name']))]) - + @testing.resolve_artifact_names def test_populate_existing(self): canary = self._fixture() - + sess = Session() - + u1 = User(name='u1') sess.add(u1) sess.commit() - + sess.query(User).populate_existing().first() eq_(canary, [('refresh', None)]) - + class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): run_inserts = None @@ -398,42 +398,42 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): def test_class_listen(self): def my_listener(*arg, **kw): pass - + event.listen(Session, 'before_flush', my_listener) - + s = Session() assert my_listener in s.dispatch.before_flush - + def test_sessionmaker_listen(self): """test that listen can be applied to individual scoped_session() classes.""" - + def my_listener_one(*arg, **kw): pass def my_listener_two(*arg, **kw): pass - + S1 = sessionmaker() S2 = sessionmaker() - + event.listen(Session, 'before_flush', my_listener_one) event.listen(S1, 'before_flush', my_listener_two) - + s1 = S1() assert my_listener_one in s1.dispatch.before_flush assert my_listener_two in s1.dispatch.before_flush - + s2 = S2() assert my_listener_one in s2.dispatch.before_flush assert my_listener_two not in s2.dispatch.before_flush - + def test_scoped_session_invalid_callable(self): from sqlalchemy.orm import scoped_session - + def my_listener_one(*arg, **kw): pass - + scope = scoped_session(lambda:Session()) - + assert_raises_message( sa.exc.ArgumentError, "Session event listen on a ScopedSession " @@ -443,41 +443,41 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): def test_scoped_session_invalid_class(self): from sqlalchemy.orm import scoped_session - + def my_listener_one(*arg, **kw): pass - + class NotASession(object): def __call__(self): return Session() - + scope = scoped_session(NotASession) - + assert_raises_message( sa.exc.ArgumentError, "Session event listen on a ScopedSession " "requries that its creation callable is a Session subclass.", event.listen, scope, "before_flush", my_listener_one ) - + def test_scoped_session_listen(self): from sqlalchemy.orm import scoped_session - + def my_listener_one(*arg, **kw): pass - + scope = scoped_session(sessionmaker()) event.listen(scope, "before_flush", my_listener_one) - + assert my_listener_one in scope().dispatch.before_flush - + def _listener_fixture(self, **kw): canary = [] def listener(name): def go(*arg, **kw): canary.append(name) return go - + sess = Session(**kw) for evt in [ @@ -493,16 +493,16 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): 'after_bulk_delete' ]: event.listen(sess, evt, listener(evt)) - + return sess, canary - + @testing.resolve_artifact_names def test_flush_autocommit_hook(self): - + mapper(User, users) sess, canary = self._listener_fixture(autoflush=False, autocommit=True) - + u = User(name='u1') sess.add(u) sess.flush() @@ -524,7 +524,7 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): sess.flush() eq_(canary, ['after_attach', 'before_flush', 'after_begin', 'after_flush', 'after_flush_postexec']) - + @testing.resolve_artifact_names def test_flush_in_commit_hook(self): sess, canary = self._listener_fixture() @@ -534,17 +534,17 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): sess.add(u) sess.flush() canary[:] = [] - + u.name = 'ed' sess.commit() eq_(canary, ['before_commit', 'before_flush', 'after_flush', 'after_flush_postexec', 'after_commit']) - + def test_standalone_on_commit_hook(self): sess, canary = self._listener_fixture() sess.commit() eq_(canary, ['before_commit', 'after_commit']) - + @testing.resolve_artifact_names def test_on_bulk_update_hook(self): sess, canary = self._listener_fixture() @@ -558,7 +558,7 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): mapper(User, users) sess.query(User).delete() eq_(canary, ['after_begin', 'after_bulk_delete']) - + def test_connection_emits_after_begin(self): sess, canary = self._listener_fixture(bind=testing.db) conn = sess.connection() @@ -571,7 +571,7 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): def before_flush(session, flush_context, objects): session.flush() - + sess = Session() event.listen(sess, 'before_flush', before_flush) sess.add(User(name='foo')) @@ -580,9 +580,9 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): @testing.resolve_artifact_names def test_before_flush_affects_flush_plan(self): - + mapper(User, users) - + def before_flush(session, flush_context, objects): for obj in list(session.new) + list(session.dirty): if isinstance(obj, User): @@ -592,7 +592,7 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): x = session.query(User).filter(User.name == 'another %s' % obj.name).one() session.delete(x) - + sess = Session() event.listen(sess, 'before_flush', before_flush) @@ -605,7 +605,7 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): User(name='u1') ] ) - + sess.flush() eq_(sess.query(User).order_by(User.name).all(), [ @@ -635,21 +635,21 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): @testing.resolve_artifact_names def test_before_flush_affects_dirty(self): mapper(User, users) - + def before_flush(session, flush_context, objects): for obj in list(session.identity_map.values()): obj.name += " modified" - + sess = Session(autoflush=True) event.listen(sess, 'before_flush', before_flush) - + u = User(name='u1') sess.add(u) sess.flush() eq_(sess.query(User).order_by(User.name).all(), [User(name='u1')] ) - + sess.add(User(name='u2')) sess.flush() sess.expunge_all() @@ -659,15 +659,15 @@ class SessionEventsTest(_RemoveListeners, _fixtures.FixtureTest): User(name='u2') ] ) - - + + class MapperExtensionTest(_fixtures.FixtureTest): """Superceded by MapperEventsTest - test backwards compatiblity of MapperExtension.""" - + run_inserts = None - + def extension(self): methods = [] @@ -787,7 +787,7 @@ class MapperExtensionTest(_fixtures.FixtureTest): def test_before_after_only_collection(self): """before_update is called on parent for collection modifications, after_update is called even if no columns were updated. - + """ Ext1, methods1 = self.extension() @@ -848,13 +848,13 @@ class MapperExtensionTest(_fixtures.FixtureTest): 'create_instance', 'populate_instance', 'reconstruct_instance', 'append_result', 'before_update', 'after_update', 'before_delete', 'after_delete']) - + @testing.resolve_artifact_names def test_create_instance(self): class CreateUserExt(sa.orm.MapperExtension): def create_instance(self, mapper, selectcontext, row, class_): return User.__new__(User) - + mapper(User, users, extension=CreateUserExt()) sess = create_session() u1 = User() @@ -873,30 +873,30 @@ class AttributeExtensionTest(_base.MappedTest): Column('id', Integer, primary_key=True), Column('type', String(40)), Column('data', String(50)) - + ) @testing.resolve_artifact_names def test_cascading_extensions(self): ext_msg = [] - + class Ex1(sa.orm.AttributeExtension): def set(self, state, value, oldvalue, initiator): ext_msg.append("Ex1 %r" % value) return "ex1" + value - + class Ex2(sa.orm.AttributeExtension): def set(self, state, value, oldvalue, initiator): ext_msg.append("Ex2 %r" % value) return "ex2" + value - + class A(_base.BasicEntity): pass class B(A): pass class C(B): pass - + mapper(A, t1, polymorphic_on=t1.c.type, polymorphic_identity='a', properties={ 'data':column_property(t1.c.data, extension=Ex1()) }) @@ -904,26 +904,26 @@ class AttributeExtensionTest(_base.MappedTest): mc = mapper(C, polymorphic_identity='c', inherits=B, properties={ 'data':column_property(t1.c.data, extension=Ex2()) }) - + a1 = A(data='a1') b1 = B(data='b1') c1 = C(data='c1') - + eq_(a1.data, 'ex1a1') eq_(b1.data, 'ex1b1') eq_(c1.data, 'ex2c1') - + a1.data = 'a2' b1.data='b2' c1.data = 'c2' eq_(a1.data, 'ex1a2') eq_(b1.data, 'ex1b2') eq_(c1.data, 'ex2c2') - + eq_(ext_msg, ["Ex1 'a1'", "Ex1 'b1'", "Ex2 'c1'", "Ex1 'a2'", "Ex1 'b2'", "Ex2 'c2'"]) - + class SessionExtensionTest(_fixtures.FixtureTest): run_inserts = None @@ -1013,7 +1013,7 @@ class SessionExtensionTest(_fixtures.FixtureTest): class MyExt1(sa.orm.session.SessionExtension): def before_commit(self, session): log.append('before_commit_one') - + class MyExt2(sa.orm.session.SessionExtension): def before_commit(self, session): @@ -1028,4 +1028,4 @@ class SessionExtensionTest(_fixtures.FixtureTest): 'before_commit_one', 'before_commit_two', ] - + diff --git a/test/orm/test_expire.py b/test/orm/test_expire.py index d691e7270..68b254725 100644 --- a/test/orm/test_expire.py +++ b/test/orm/test_expire.py @@ -92,7 +92,7 @@ class ExpireTest(_fixtures.FixtureTest): # trick the "deleted" flag so we can re-add for the sake # of this test del attributes.instance_state(u).deleted - + # add it back s.add(u) # nope, raises ObjectDeletedError @@ -101,7 +101,7 @@ class ExpireTest(_fixtures.FixtureTest): # do a get()/remove u from session again assert s.query(User).get(10) is None assert u not in s - + s.rollback() assert u in s @@ -112,9 +112,9 @@ class ExpireTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_deferred(self): """test that unloaded, deferred attributes aren't included in the expiry list.""" - + mapper(Order, orders, properties={'description':deferred(orders.c.description)}) - + s = create_session() o1 = s.query(Order).first() assert 'description' not in o1.__dict__ @@ -122,7 +122,7 @@ class ExpireTest(_fixtures.FixtureTest): assert o1.isopen is not None assert 'description' not in o1.__dict__ assert o1.description - + @testing.resolve_artifact_names def test_lazyload_autoflushes(self): mapper(User, users, properties={ @@ -150,7 +150,7 @@ class ExpireTest(_fixtures.FixtureTest): def test_refresh_collection_exception(self): """test graceful failure for currently unsupported immediate refresh of a collection""" - + mapper(User, users, properties={ 'addresses':relationship(Address, order_by=addresses.c.email_address) }) @@ -160,11 +160,11 @@ class ExpireTest(_fixtures.FixtureTest): assert_raises_message(sa_exc.InvalidRequestError, "properties specified for refresh", s.refresh, u, ['addresses']) - + # in contrast to a regular query with no columns assert_raises_message(sa_exc.InvalidRequestError, "no columns with which to SELECT", s.query().all) - + @testing.resolve_artifact_names def test_refresh_cancels_expire(self): mapper(User, users) @@ -229,7 +229,7 @@ class ExpireTest(_fixtures.FixtureTest): assert 'name' not in u.__dict__ sess.add(u) assert u.name == 'jack' - + @testing.resolve_artifact_names def test_no_instance_key_no_pk(self): # same as test_no_instance_key, but the PK columns @@ -245,7 +245,7 @@ class ExpireTest(_fixtures.FixtureTest): sess.add(u) assert_raises(sa_exc.InvalidRequestError, getattr, u, 'name') - + @testing.resolve_artifact_names def test_expire_preserves_changes(self): """test that the expire load operation doesn't revert post-expire changes""" @@ -350,7 +350,7 @@ class ExpireTest(_fixtures.FixtureTest): def test_refresh_cascade_pending(self): cascade = 'save-update, refresh-expire' self._test_cascade_to_pending(cascade, False) - + @testing.resolve_artifact_names def _test_cascade_to_pending(self, cascade, expire_or_refresh): mapper(User, users, properties={ @@ -361,7 +361,7 @@ class ExpireTest(_fixtures.FixtureTest): u = s.query(User).get(8) a = Address(id=12, email_address='foobar') - + u.addresses.append(a) if expire_or_refresh: s.expire(u) @@ -371,7 +371,7 @@ class ExpireTest(_fixtures.FixtureTest): assert a not in s else: assert a in s - + assert a not in u.addresses s.flush() @@ -759,9 +759,9 @@ class ExpireTest(_fixtures.FixtureTest): """Behavioral test to verify the current activity of loader callables.""" mapper(User, users) - + sess = create_session() - + # deferred attribute option, gets the LoadDeferredColumns # callable u1 = sess.query(User).options(defer(User.name)).first() @@ -769,14 +769,14 @@ class ExpireTest(_fixtures.FixtureTest): attributes.instance_state(u1).callables['name'], strategies.LoadDeferredColumns ) - + # expire the attr, it gets the InstanceState callable sess.expire(u1, ['name']) assert isinstance( attributes.instance_state(u1).callables['name'], state.InstanceState ) - + # load it, callable is gone u1.name assert 'name' not in attributes.instance_state(u1).callables @@ -789,28 +789,28 @@ class ExpireTest(_fixtures.FixtureTest): attributes.instance_state(u1).callables['name'], state.InstanceState ) - + # load over it. everything normal. sess.query(User).first() assert 'name' not in attributes.instance_state(u1).callables - + sess.expunge_all() u1 = sess.query(User).first() # for non present, still expires the same way del u1.name sess.expire(u1) assert 'name' in attributes.instance_state(u1).callables - + @testing.resolve_artifact_names def test_state_deferred_to_col(self): """Behavioral test to verify the current activity of loader callables.""" - + mapper(User, users, properties={'name':deferred(users.c.name)}) sess = create_session() u1 = sess.query(User).options(undefer(User.name)).first() assert 'name' not in attributes.instance_state(u1).callables - + # mass expire, the attribute was loaded, # the attribute gets the callable sess.expire(u1) @@ -822,7 +822,7 @@ class ExpireTest(_fixtures.FixtureTest): # load it, callable is gone u1.name assert 'name' not in attributes.instance_state(u1).callables - + # mass expire, attribute was loaded but then deleted, # the callable goes away - the state wants to flip # it back to its "deferred" loader. @@ -847,7 +847,7 @@ class ExpireTest(_fixtures.FixtureTest): mapper(User, users, properties={'addresses':relationship(Address, lazy='noload')}) mapper(Address, addresses) - + sess = create_session() u1 = sess.query(User).options(lazyload(User.addresses)).first() assert isinstance( @@ -860,11 +860,11 @@ class ExpireTest(_fixtures.FixtureTest): attributes.instance_state(u1).callables['addresses'], strategies.LoadLazyAttribute ) - + # load over it. callable goes away. sess.query(User).first() assert 'addresses' not in attributes.instance_state(u1).callables - + sess.expunge_all() u1 = sess.query(User).options(lazyload(User.addresses)).first() sess.expire(u1, ['addresses']) @@ -872,13 +872,13 @@ class ExpireTest(_fixtures.FixtureTest): attributes.instance_state(u1).callables['addresses'], strategies.LoadLazyAttribute ) - + # load the attr, goes away u1.addresses assert 'addresses' not in attributes.instance_state(u1).callables - - - + + + class PolymorphicExpireTest(_base.MappedTest): run_inserts = 'once' run_deletes = None @@ -919,13 +919,13 @@ class PolymorphicExpireTest(_base.MappedTest): {'person_id':2, 'status':'new engineer'}, {'person_id':3, 'status':'old engineer'}, ) - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): mapper(Person, people, polymorphic_on=people.c.type, polymorphic_identity='person') mapper(Engineer, engineers, inherits=Person, polymorphic_identity='engineer') - + @testing.resolve_artifact_names def test_poly_deferred(self): @@ -965,7 +965,7 @@ class PolymorphicExpireTest(_base.MappedTest): @testing.resolve_artifact_names def test_no_instance_key(self): - + sess = create_session() e1 = sess.query(Engineer).get(2) @@ -975,7 +975,7 @@ class PolymorphicExpireTest(_base.MappedTest): assert 'name' not in e1.__dict__ sess.add(e1) assert e1.name == 'engineer1' - + @testing.resolve_artifact_names def test_no_instance_key(self): # same as test_no_instance_key, but the PK columns @@ -996,7 +996,7 @@ class ExpiredPendingTest(_fixtures.FixtureTest): run_setup_classes = 'once' run_setup_mappers = None run_inserts = None - + @testing.resolve_artifact_names def test_expired_pending(self): mapper(User, users, properties={ @@ -1008,7 +1008,7 @@ class ExpiredPendingTest(_fixtures.FixtureTest): a1 = Address(email_address='a1') sess.add(a1) sess.flush() - + u1 = User(name='u1') a1.user = u1 sess.flush() @@ -1025,17 +1025,17 @@ class ExpiredPendingTest(_fixtures.FixtureTest): # expire u1.addresses again. this expires # "pending" as well. sess.expire(u1, ['addresses']) - + # insert a new row sess.execute(addresses.insert(), dict(email_address='a3', user_id=u1.id)) - + # only two addresses pulled from the DB, no "pending" assert len(u1.addresses) == 2 - + sess.flush() sess.expire_all() assert len(u1.addresses) == 3 - + class RefreshTest(_fixtures.FixtureTest): diff --git a/test/orm/test_extendedattr.py b/test/orm/test_extendedattr.py index c20cad0da..0cc6a957b 100644 --- a/test/orm/test_extendedattr.py +++ b/test/orm/test_extendedattr.py @@ -109,18 +109,18 @@ class UserDefinedExtensionTest(_base.ORMTest): def test_instance_dict(self): class User(MyClass): pass - + instrumentation.register_class(User) attributes.register_attribute(User, 'user_id', uselist = False, useobject=False) attributes.register_attribute(User, 'user_name', uselist = False, useobject=False) attributes.register_attribute(User, 'email_address', uselist = False, useobject=False) - + u = User() u.user_id = 7 u.user_name = 'john' u.email_address = 'lala@123.com' self.assert_(u.__dict__ == {'_my_state':u._my_state, '_goofy_dict':{'user_id':7, 'user_name':'john', 'email_address':'lala@123.com'}}, u.__dict__) - + def test_basic(self): for base in (object, MyBaseClass, MyClass): class User(base): @@ -158,7 +158,7 @@ class UserDefinedExtensionTest(_base.ORMTest): manager.deferred_scalar_loader = loader attributes.register_attribute(Foo, 'a', uselist=False, useobject=False) attributes.register_attribute(Foo, 'b', uselist=False, useobject=False) - + assert Foo in instrumentation.instrumentation_registry._state_finders f = Foo() attributes.instance_state(f).expire(attributes.instance_dict(f), set()) diff --git a/test/orm/test_froms.py b/test/orm/test_froms.py index 6c86fa7ec..f07ddc7de 100644 --- a/test/orm/test_froms.py +++ b/test/orm/test_froms.py @@ -62,9 +62,9 @@ class QueryTest(_fixtures.FixtureTest): class RawSelectTest(QueryTest, AssertsCompiledSQL): """compare a bunch of select() tests with the equivalent Query using straight table/columns. - + Results should be the same as Query should act as a select() pass-thru for ClauseElement entities. - + """ def test_select(self): sess = create_session() @@ -86,7 +86,7 @@ class RawSelectTest(QueryTest, AssertsCompiledSQL): # TODO: can we detect only one table in the "froms" and then turn off use_labels ? s = sess.query(addresses.c.id.label('id'), addresses.c.email_address.label('email')).\ filter(addresses.c.user_id==users.c.id).correlate(users).statement.alias() - + self.assert_compile(sess.query(users, s.c.email).select_from(users.join(s, s.c.id==users.c.id)).with_labels().statement, "SELECT users.id AS users_id, users.name AS users_name, anon_1.email AS anon_1_email " "FROM users JOIN (SELECT addresses.id AS id, addresses.email_address AS email FROM addresses " @@ -98,7 +98,7 @@ class RawSelectTest(QueryTest, AssertsCompiledSQL): self.assert_compile(sess.query(x).filter(x==5).statement, "SELECT lala(users.id) AS foo FROM users WHERE lala(users.id) = :param_1", dialect=default.DefaultDialect()) - self.assert_compile(sess.query(func.sum(x).label('bar')).statement, + self.assert_compile(sess.query(func.sum(x).label('bar')).statement, "SELECT sum(lala(users.id)) AS bar FROM users", dialect=default.DefaultDialect()) @@ -109,7 +109,7 @@ class FromSelfTest(QueryTest, AssertsCompiledSQL): assert [User(id=8), User(id=9)] == create_session().query(User).order_by(User.id).slice(1,3).from_self().all() assert [User(id=8)] == list(create_session().query(User).filter(User.id.in_([8,9])).from_self().order_by(User.id)[0:1]) - + def test_join(self): assert [ (User(id=8), Address(id=2)), @@ -118,7 +118,7 @@ class FromSelfTest(QueryTest, AssertsCompiledSQL): (User(id=9), Address(id=5)) ] == create_session().query(User).filter(User.id.in_([8,9])).from_self().\ join('addresses').add_entity(Address).order_by(User.id, Address.id).all() - + def test_group_by(self): eq_( create_session().query(Address.user_id, func.count(Address.id).label('count')).\ @@ -132,14 +132,14 @@ class FromSelfTest(QueryTest, AssertsCompiledSQL): group_by(Address.user_id).order_by(Address.user_id).all(), [(7, 1), (8, 3), (9, 1)] ) - + def test_no_joinedload(self): """test that joinedloads are pushed outwards and not rendered in subqueries.""" - + s = create_session() - + oracle_as = not testing.against('oracle') and "AS " or "" - + self.assert_compile( s.query(User).options(joinedload(User.addresses)).from_self().statement, "SELECT anon_1.users_id, anon_1.users_name, addresses_1.id, addresses_1.user_id, "\ @@ -148,12 +148,12 @@ class FromSelfTest(QueryTest, AssertsCompiledSQL): 'oracle_as':oracle_as } ) - + def test_aliases(self): """test that aliased objects are accessible externally to a from_self() call.""" - + s = create_session() - + ualias = aliased(User) eq_( s.query(User, ualias).filter(User.id > ualias.id).from_self(User.name, ualias.name). @@ -184,8 +184,8 @@ class FromSelfTest(QueryTest, AssertsCompiledSQL): (u'jack', u'ed@wood.com'), (u'jack', u'fred@fred.com')] ) - - + + def test_multiple_entities(self): sess = create_session() @@ -199,14 +199,14 @@ class FromSelfTest(QueryTest, AssertsCompiledSQL): eq_( sess.query(User, Address).filter(User.id==Address.user_id).filter(Address.id.in_([2, 5])).from_self().options(joinedload('addresses')).first(), - + # order_by(User.id, Address.id).first(), (User(id=8, addresses=[Address(), Address(), Address()]), Address(id=2)), ) def test_multiple_with_column_entities(self): sess = create_session() - + eq_( sess.query(User.id).from_self().\ add_column(func.count().label('foo')).\ @@ -216,7 +216,7 @@ class FromSelfTest(QueryTest, AssertsCompiledSQL): [ (7,1), (8, 1), (9, 1), (10, 1) ] - + ) class AddEntityEquivalenceTest(_base.MappedTest, AssertsCompiledSQL): @@ -252,16 +252,16 @@ class AddEntityEquivalenceTest(_base.MappedTest, AssertsCompiledSQL): def setup_classes(cls): class A(_fixtures.Base): pass - + class B(_fixtures.Base): pass - + class C(B): pass - + class D(A): pass - + mapper(A, a, polymorphic_identity='a', polymorphic_on=a.c.type, @@ -276,7 +276,7 @@ class AddEntityEquivalenceTest(_base.MappedTest, AssertsCompiledSQL): ) mapper(C, c, inherits=B, polymorphic_identity='c') mapper(D, d, inherits=A, polymorphic_identity='d') - + @classmethod @testing.resolve_artifact_names def insert_data(cls): @@ -288,11 +288,11 @@ class AddEntityEquivalenceTest(_base.MappedTest, AssertsCompiledSQL): A(name='a2') ]) sess.flush() - + @testing.resolve_artifact_names def test_add_entity_equivalence(self): sess = create_session() - + for q in [ sess.query( A,B).join( A.link), sess.query( A).join( A.link).add_entity(B), @@ -317,8 +317,8 @@ class AddEntityEquivalenceTest(_base.MappedTest, AssertsCompiledSQL): A(bid=2, id=1, name=u'a1', type=u'a') )] ) - - + + class InstancesTest(QueryTest, AssertsCompiledSQL): def test_from_alias(self): @@ -388,7 +388,7 @@ class InstancesTest(QueryTest, AssertsCompiledSQL): 'users.id = addresses.user_id ORDER BY ' 'users.id, addresses.id', dialect=default.DefaultDialect()) - + def go(): assert self.static.user_address_result == q.all() self.assert_sql_count(testing.db, go, 1) @@ -484,7 +484,7 @@ class InstancesTest(QueryTest, AssertsCompiledSQL): def test_mixed_eager_contains_with_limit(self): sess = create_session() - + q = sess.query(User) def go(): # outerjoin to User.orders, offset 1/limit 2 so we get user @@ -529,8 +529,8 @@ class InstancesTest(QueryTest, AssertsCompiledSQL): , isopen=0, id=5)])]) self.assert_sql_count(testing.db, go, 1) - - + + class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): def test_values(self): @@ -542,7 +542,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): q = sess.query(User) q2 = q.select_from(sel).values(User.name) eq_(list(q2), [(u'jack',), (u'ed',)]) - + q = sess.query(User) q2 = q.order_by(User.id).\ values(User.name, User.name + " " + cast(User.id, String(50))) @@ -551,7 +551,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): [(u'jack', u'jack 7'), (u'ed', u'ed 8'), (u'fred', u'fred 9'), (u'chuck', u'chuck 10')] ) - + q2 = q.join('addresses').\ filter(User.name.like('%e%')).\ order_by(User.id, Address.id).\ @@ -559,20 +559,20 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): eq_(list(q2), [(u'ed', u'ed@wood.com'), (u'ed', u'ed@bettyboop.com'), (u'ed', u'ed@lala.com'), (u'fred', u'fred@fred.com')]) - + q2 = q.join('addresses').\ filter(User.name.like('%e%')).\ order_by(desc(Address.email_address)).\ slice(1, 3).values(User.name, Address.email_address) eq_(list(q2), [(u'ed', u'ed@wood.com'), (u'ed', u'ed@lala.com')]) - + adalias = aliased(Address) q2 = q.join(adalias, 'addresses').\ filter(User.name.like('%e%')).\ values(User.name, adalias.email_address) eq_(list(q2), [(u'ed', u'ed@wood.com'), (u'ed', u'ed@bettyboop.com'), (u'ed', u'ed@lala.com'), (u'fred', u'fred@fred.com')]) - + q2 = q.values(func.count(User.name)) assert q2.next() == (4,) @@ -637,10 +637,10 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): def test_correlated_subquery(self): """test that a subquery constructed from ORM attributes doesn't leak out those entities to the outermost query. - + """ sess = create_session() - + subq = select([func.count()]).\ where(User.id==Address.user_id).\ correlate(users).\ @@ -668,17 +668,17 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): def test_tuple_labeling(self): sess = create_session() - + # test pickle + all the protocols ! for pickled in False, -1, 0, 1, 2: for row in sess.query(User, Address).join(User.addresses).all(): if pickled is not False: row = util.pickle.loads(util.pickle.dumps(row, pickled)) - + eq_(row.keys(), ['User', 'Address']) eq_(row.User, row[0]) eq_(row.Address, row[1]) - + for row in sess.query(User.name, User.id.label('foobar')): if pickled is not False: row = util.pickle.loads(util.pickle.dumps(row, pickled)) @@ -707,22 +707,22 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): eq_(row.keys(), ['User', 'orders']) eq_(row.User, row[0]) eq_(row.orders, row[1]) - + # test here that first col is not labeled, only # one name in keys, matches correctly for row in sess.query(User.name + 'hoho', User.name): eq_(row.keys(), ['name']) eq_(row[0], row.name + 'hoho') - + if pickled is not False: ret = sess.query(User, Address).join(User.addresses).all() util.pickle.loads(util.pickle.dumps(ret, pickled)) - + def test_column_queries(self): sess = create_session() eq_(sess.query(User.name).all(), [(u'jack',), (u'ed',), (u'fred',), (u'chuck',)]) - + sel = users.select(User.id.in_([7, 8])).alias() q = sess.query(User.name) q2 = q.select_from(sel).all() @@ -733,7 +733,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): (u'ed', u'ed@bettyboop.com'), (u'ed', u'ed@lala.com'), (u'fred', u'fred@fred.com') ]) - + eq_(sess.query(User.name, func.count(Address.email_address)).\ outerjoin(User.addresses).group_by(User.id, User.name).\ order_by(User.id).all(), @@ -753,7 +753,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): [(1, User(name='jack',id=7)), (3, User(name='ed',id=8)), (1, User(name='fred',id=9)), (0, User(name='chuck',id=10))] ) - + adalias = aliased(Address) eq_(sess.query(User, func.count(adalias.email_address)).\ outerjoin(adalias, 'addresses').group_by(User).\ @@ -784,7 +784,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): (User(name=u'chuck',id=10), None) ] ) - + # anon + select from aliasing eq_( sess.query(User).join(User.addresses, aliased=True).\ @@ -837,17 +837,17 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): def test_column_from_limited_joinedload(self): sess = create_session() - + def go(): results = sess.query(User).limit(1).\ options(joinedload('addresses')).\ add_column(User.name).all() eq_(results, [(User(name='jack'), 'jack')]) self.assert_sql_count(testing.db, go, 1) - + @testing.fails_on('postgresql+pg8000', "'type oid 705 not mapped to py type' (due to literal)") def test_self_referential(self): - + sess = create_session() oalias = aliased(Order) @@ -858,12 +858,12 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): sess.query(Order, oalias).from_self().filter(Order.user_id==oalias.user_id).\ filter(Order.user_id==7).filter(Order.id>oalias.id).\ order_by(Order.id, oalias.id), - - # same thing, but reversed. + + # same thing, but reversed. sess.query(oalias, Order).from_self().filter(oalias.user_id==Order.user_id).\ filter(oalias.user_id==7).filter(Order.id<oalias.id).\ order_by(oalias.id, Order.id), - + # here we go....two layers of aliasing sess.query(Order, oalias).filter(Order.user_id==oalias.user_id).\ filter(Order.user_id==7).filter(Order.id>oalias.id).\ @@ -877,7 +877,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): limit(10).options(joinedload(Order.items)), ]: - + eq_( q.all(), [ @@ -886,11 +886,11 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): (Order(address_id=None,description=u'order 5',isopen=0,user_id=7,id=5), Order(address_id=1,description=u'order 1',isopen=0,user_id=7,id=1)), (Order(address_id=None,description=u'order 5',isopen=0,user_id=7,id=5), - Order(address_id=1,description=u'order 3',isopen=1,user_id=7,id=3)) + Order(address_id=1,description=u'order 3',isopen=1,user_id=7,id=3)) ] ) - - + + # ensure column expressions are taken from inside the subquery, not restated at the top q = sess.query(Order.id, Order.description, literal_column("'q'").label('foo')).\ filter(Order.description == u'order 3').from_self() @@ -908,8 +908,8 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): q.all(), [(3, u'order 3', 'q')] ) - - + + def test_multi_mappers(self): test_session = create_session() @@ -982,9 +982,9 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): def test_with_entities(self): sess = create_session() - + q = sess.query(User).filter(User.id==7).order_by(User.name) - + self.assert_compile( q.with_entities(User.id,Address).\ filter(Address.user_id == User.id), @@ -996,8 +996,8 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): 'addresses.user_id = users.id ORDER BY ' 'users.name', use_default_dialect=True) - - + + def test_multi_columns(self): sess = create_session() @@ -1011,14 +1011,14 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): def test_add_multi_columns(self): """test that add_column accepts a FROM clause.""" - + sess = create_session() - + eq_( sess.query(User.id).add_column(users).all(), [(7, 7, u'jack'), (8, 8, u'ed'), (9, 9, u'fred'), (10, 10, u'chuck')] ) - + def test_multi_columns_2(self): """test aliased/nonalised joins with the usage of add_column()""" sess = create_session() @@ -1035,7 +1035,7 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): add_column(func.count(Address.id).label('count')) eq_(q.all(), expected) sess.expunge_all() - + adalias = aliased(Address) q = sess.query(User) q = q.group_by(users).order_by(User.id).outerjoin(adalias, 'addresses').\ @@ -1131,7 +1131,7 @@ class SelectFromTest(QueryTest, AssertsCompiledSQL): def test_join_mapper_order_by(self): """test that mapper-level order_by is adapted to a selectable.""" - + mapper(User, users, order_by=users.c.id) sel = users.select(users.c.id.in_([7, 8])) @@ -1145,14 +1145,14 @@ class SelectFromTest(QueryTest, AssertsCompiledSQL): def test_differentiate_self_external(self): """test some different combinations of joining a table to a subquery of itself.""" - + mapper(User, users) - + sess = create_session() sel = sess.query(User).filter(User.id.in_([7, 8])).subquery() ualias = aliased(User) - + self.assert_compile( sess.query(User).join(sel, User.id>sel.c.id), "SELECT users.id AS users_id, users.name AS users_name FROM " @@ -1160,7 +1160,7 @@ class SelectFromTest(QueryTest, AssertsCompiledSQL): "users WHERE users.id IN (:id_1, :id_2)) AS anon_1 ON users.id > anon_1.id", use_default_dialect=True ) - + self.assert_compile( sess.query(ualias).select_from(sel).filter(ualias.id>sel.c.id), "SELECT users_1.id AS users_1_id, users_1.name AS users_1_name FROM " @@ -1188,8 +1188,8 @@ class SelectFromTest(QueryTest, AssertsCompiledSQL): "IN (:id_1, :id_2)) AS anon_1 JOIN users AS users_1 ON users_1.id > anon_1.id", use_default_dialect=True ) - - + + # this one uses an explicit join(left, right, onclause) so works self.assert_compile( sess.query(ualias).select_from(join(sel, ualias, ualias.id>sel.c.id)), @@ -1198,9 +1198,9 @@ class SelectFromTest(QueryTest, AssertsCompiledSQL): "IN (:id_1, :id_2)) AS anon_1 JOIN users AS users_1 ON users_1.id > anon_1.id", use_default_dialect=True ) - - - + + + def test_join_no_order_by(self): mapper(User, users) @@ -1242,7 +1242,7 @@ class SelectFromTest(QueryTest, AssertsCompiledSQL): (User(name='ed',id=8), Address(user_id=8,email_address='ed@lala.com',id=4)) ] ) - + def test_more_joins(self): mapper(User, users, properties={ @@ -1321,7 +1321,7 @@ class SelectFromTest(QueryTest, AssertsCompiledSQL): ]) ]) self.assert_sql_count(testing.db, go, 1) - + sess.expunge_all() sel2 = orders.select(orders.c.id.in_([1,2,3])) eq_(sess.query(Order).select_from(sel2).\ @@ -1386,7 +1386,7 @@ class CustomJoinTest(QueryTest): closed_orders = relationship(Order, primaryjoin = and_(orders.c.isopen == 0, users.c.id==orders.c.user_id), lazy='select') )) q = create_session().query(User) - + eq_( q.join('open_orders', 'items', aliased=True).filter(Item.id==4).\ join('closed_orders', 'items', aliased=True).filter(Item.id==3).all(), @@ -1407,7 +1407,7 @@ class ExternalColumnsTest(QueryTest): def test_external_columns(self): """test querying mappings that reference external columns or selectables.""" - + mapper(User, users, properties={ 'concat': column_property((users.c.id * 2)), 'count': column_property( @@ -1421,7 +1421,7 @@ class ExternalColumnsTest(QueryTest): }) sess = create_session() - + sess.query(Address).options(joinedload('user')).all() eq_(sess.query(User).all(), @@ -1451,7 +1451,7 @@ class ExternalColumnsTest(QueryTest): order_by(Address.id).all(), address_result) self.assert_sql_count(testing.db, go, 1) - + ualias = aliased(User) eq_( sess.query(Address, ualias).join(ualias, 'user').all(), @@ -1559,16 +1559,16 @@ class TestOverlyEagerEquivalentCols(_base.MappedTest): pass class Sub2(_base.ComparableEntity): pass - + mapper(Base, base, properties={ 'sub1':relationship(Sub1), 'sub2':relationship(Sub2) }) - + mapper(Sub1, sub1) mapper(Sub2, sub2) sess = create_session() - + s11 = Sub1(data='s11') s12 = Sub1(data='s12') s2 = Sub2(data='s2') @@ -1577,12 +1577,12 @@ class TestOverlyEagerEquivalentCols(_base.MappedTest): sess.add(b1) sess.add(b2) sess.flush() - + # theres an overlapping ForeignKey here, so not much option except # to artifically control the flush order b2.sub2 = [s2] sess.flush() - + q = sess.query(Base).outerjoin('sub2', aliased=True) assert sub1.c.id not in q._filter_aliases.equivalents diff --git a/test/orm/test_generative.py b/test/orm/test_generative.py index e3c5eee99..79da5fc7a 100644 --- a/test/orm/test_generative.py +++ b/test/orm/test_generative.py @@ -46,11 +46,11 @@ class GenerativeQueryTest(_base.MappedTest): sess = create_session() query = sess.query(Foo).order_by(Foo.id) orig = query.all() - + assert query[1] == orig[1] assert query[-4] == orig[-4] assert query[-1] == orig[-1] - + assert list(query[10:20]) == orig[10:20] assert list(query[10:]) == orig[10:] assert list(query[:10]) == orig[:10] @@ -61,7 +61,7 @@ class GenerativeQueryTest(_base.MappedTest): assert list(query[-2:-5]) == orig[-2:-5] assert list(query[-5:-2]) == orig[-5:-2] assert list(query[:-2]) == orig[:-2] - + assert query[10:20][5] == orig[10:20][5] @testing.uses_deprecated('Call to deprecated function apply_max') @@ -71,7 +71,7 @@ class GenerativeQueryTest(_base.MappedTest): query = sess.query(Foo) assert query.count() == 100 assert sess.query(func.min(foo.c.bar)).filter(foo.c.bar<30).one() == (0,) - + assert sess.query(func.max(foo.c.bar)).filter(foo.c.bar<30).one() == (29,) # Py3K #assert query.filter(foo.c.bar<30).values(sa.func.max(foo.c.bar)).__next__()[0] == 29 @@ -80,7 +80,7 @@ class GenerativeQueryTest(_base.MappedTest): assert query.filter(foo.c.bar<30).values(sa.func.max(foo.c.bar)).next()[0] == 29 assert query.filter(foo.c.bar<30).values(sa.func.max(foo.c.bar)).next()[0] == 29 # end Py2K - + @testing.fails_if(lambda:testing.against('mysql+mysqldb') and testing.db.dialect.dbapi.version_info[:4] == (1, 2, 1, 'gamma'), "unknown incompatibility") diff --git a/test/orm/test_immediate_load.py b/test/orm/test_immediate_load.py index 66794ad4b..eb62ef40e 100644 --- a/test/orm/test_immediate_load.py +++ b/test/orm/test_immediate_load.py @@ -17,12 +17,12 @@ class ImmediateTest(_fixtures.FixtureTest): 'addresses':relationship(Address) }) sess = create_session() - + l = sess.query(User).options(immediateload(User.addresses)).filter(users.c.id==7).all() eq_(len(sess.identity_map), 2) - + sess.close() - + eq_( [User(id=7, addresses=[Address(id=1, email_address='jack@bean.com')])], l @@ -36,11 +36,11 @@ class ImmediateTest(_fixtures.FixtureTest): 'addresses':relationship(Address, lazy='immediate') }) sess = create_session() - + l = sess.query(User).filter(users.c.id==7).all() eq_(len(sess.identity_map), 2) sess.close() - + eq_( [User(id=7, addresses=[Address(id=1, email_address='jack@bean.com')])], l diff --git a/test/orm/test_instrumentation.py b/test/orm/test_instrumentation.py index 3d3c96c6a..18dca8e45 100644 --- a/test/orm/test_instrumentation.py +++ b/test/orm/test_instrumentation.py @@ -651,16 +651,16 @@ class MiscTest(_base.ORMTest): a = A() assert not a.bs - + def test_uninstrument(self): class A(object):pass - + manager = instrumentation.register_class(A) - + assert instrumentation.manager_of_class(A) is manager instrumentation.unregister_class(A) assert instrumentation.manager_of_class(A) is None - + def test_compileonattr_rel_backref_a(self): m = MetaData() t1 = Table('t1', m, diff --git a/test/orm/test_joins.py b/test/orm/test_joins.py index 5ae16919f..af6109b9a 100644 --- a/test/orm/test_joins.py +++ b/test/orm/test_joins.py @@ -61,7 +61,7 @@ class QueryTest(_fixtures.FixtureTest): class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): run_setup_mappers = 'once' - + @classmethod def define_tables(cls, metadata): Table('companies', metadata, @@ -80,12 +80,12 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): Column('engineer_name', String(50)), Column('primary_language', String(50)), ) - + Table('machines', metadata, Column('machine_id', Integer, primary_key=True, test_needs_autoincrement=True), Column('name', String(50)), Column('engineer_id', Integer, ForeignKey('engineers.person_id'))) - + Table('managers', metadata, Column('person_id', Integer, ForeignKey('people.person_id'), primary_key=True), Column('status', String(30)), @@ -101,7 +101,7 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): Column('paperwork_id', Integer, primary_key=True, test_needs_autoincrement=True), Column('description', String(50)), Column('person_id', Integer, ForeignKey('people.person_id'))) - + @classmethod @testing.resolve_artifact_names def setup_classes(cls): @@ -140,11 +140,11 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): inherits=Person, polymorphic_identity='manager') mapper(Boss, boss, inherits=Manager, polymorphic_identity='boss') mapper(Paperwork, paperwork) - + @testing.resolve_artifact_names def test_single_prop(self): sess = create_session() - + self.assert_compile( sess.query(Company).join(Company.employees), "SELECT companies.company_id AS companies_company_id, companies.name AS companies_name " @@ -176,9 +176,9 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): "WHERE companies.company_id = people.company_id AND engineers.primary_language =" " :primary_language_1", use_default_dialect=True - + ) - + @testing.resolve_artifact_names def test_single_prop_of_type(self): sess = create_session() @@ -200,7 +200,7 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): @testing.resolve_artifact_names def test_prop_with_polymorphic(self): sess = create_session() - + self.assert_compile( sess.query(Person).with_polymorphic(Manager). join('paperwork').filter(Paperwork.description.like('%review%')), @@ -216,7 +216,7 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): "ORDER BY people.person_id" , use_default_dialect=True ) - + self.assert_compile( sess.query(Person).with_polymorphic(Manager). join('paperwork', aliased=True). @@ -234,7 +234,7 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): @testing.resolve_artifact_names def test_explicit_polymorphic_join(self): sess = create_session() - + self.assert_compile( sess.query(Company).join(Engineer).filter(Engineer.engineer_name=='vlad'), "SELECT companies.company_id AS companies_company_id, companies.name AS " @@ -275,7 +275,7 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): def test_multiple_adaption(self): """test that multiple filter() adapters get chained together " and work correctly within a multiple-entry join().""" - + sess = create_session() self.assert_compile( @@ -295,7 +295,7 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): "anon_1.people_company_id WHERE anon_1.people_name = :name_1" , use_default_dialect = True ) - + mach_alias = machines.select() self.assert_compile( sess.query(Company).join(people.join(engineers), Company.employees). @@ -324,7 +324,7 @@ class InheritedJoinTest(_base.MappedTest, AssertsCompiledSQL): class JoinTest(QueryTest, AssertsCompiledSQL): - + def test_single_name(self): sess = create_session() @@ -357,21 +357,21 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "ON addresses.id = orders.address_id" , use_default_dialect=True ) - + def test_multi_tuple_form(self): """test the 'tuple' form of join, now superceded by the two-element join() form. - + Not deprecating this style as of yet. - + """ - + sess = create_session() - + #assert_raises( # sa.exc.SADeprecationWarning, # sess.query(User).join, (Order, User.id==Order.user_id) #) - + self.assert_compile( sess.query(User).join((Order, User.id==Order.user_id)), "SELECT users.id AS users_id, users.name AS users_name " @@ -390,7 +390,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "order_items_1.item_id", use_default_dialect=True ) - + # the old "backwards" form self.assert_compile( sess.query(User).join(("orders", Order)), @@ -398,7 +398,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "FROM users JOIN orders ON users.id = orders.user_id", use_default_dialect=True ) - + def test_single_prop(self): sess = create_session() self.assert_compile( @@ -424,7 +424,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "FROM orders AS orders_1 JOIN users ON users.id = orders_1.user_id" , use_default_dialect=True ) - + # another nonsensical query. (from [ticket:1537]). # in this case, the contract of "left to right" is honored self.assert_compile( @@ -434,7 +434,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "orders AS orders_2 JOIN users ON users.id = orders_2.user_id" , use_default_dialect=True ) - + self.assert_compile( sess.query(User).join(User.orders, Order.items), "SELECT users.id AS users_id, users.name AS users_name FROM users " @@ -442,7 +442,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "ON orders.id = order_items_1.order_id JOIN items ON items.id = order_items_1.item_id" , use_default_dialect=True ) - + ualias = aliased(User) self.assert_compile( sess.query(ualias).join(ualias.orders), @@ -450,7 +450,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "FROM users AS users_1 JOIN orders ON users_1.id = orders.user_id" , use_default_dialect=True ) - + # this query is somewhat nonsensical. the old system didn't render a correct # query for this. In this case its the most faithful to what was asked - # there's no linkage between User.orders and "oalias", so two FROM elements @@ -484,7 +484,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "WHERE users.name = :name_1) AS anon_1 JOIN orders ON anon_1.users_id = orders.user_id" , use_default_dialect=True ) - + self.assert_compile( sess.query(User).join(User.addresses, aliased=True).filter(Address.email_address=='foo'), "SELECT users.id AS users_id, users.name AS users_name " @@ -502,7 +502,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "WHERE items_1.id = :id_1" , use_default_dialect=True ) - + # test #1 for [ticket:1706] ualias = aliased(User) self.assert_compile( @@ -515,7 +515,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "= addresses.user_id" , use_default_dialect=True ) - + # test #2 for [ticket:1706] ualias2 = aliased(User) self.assert_compile( @@ -528,7 +528,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "ON users_2.id = addresses.user_id JOIN orders ON users_1.id = orders.user_id" , use_default_dialect=True ) - + def test_overlapping_paths(self): for aliased in (True,False): # load a user who has an order that contains item id 3 and address id 1 (order 3, owned by jack) @@ -540,10 +540,10 @@ class JoinTest(QueryTest, AssertsCompiledSQL): result = create_session().query(User).outerjoin('orders', 'items').\ filter_by(id=3).outerjoin('orders','address').filter_by(id=1).all() assert [User(id=7, name='jack')] == result - + def test_from_joinpoint(self): sess = create_session() - + for oalias,ialias in [(True, True), (False, False), (True, False), (False, True)]: eq_( sess.query(User).join('orders', aliased=oalias).\ @@ -563,7 +563,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): filter(Item.description=='item 4').all(), [] ) - + orderalias = aliased(Order) itemalias = aliased(Item) eq_( @@ -579,11 +579,11 @@ class JoinTest(QueryTest, AssertsCompiledSQL): filter(itemalias.description=='item 4').all(), [] ) - + def test_join_nonmapped_column(self): """test that the search for a 'left' doesn't trip on non-mapped cols""" sess = create_session() - + # intentionally join() with a non-existent "left" side self.assert_compile( sess.query(User.id, literal_column('foo')).join(Order.user), @@ -591,13 +591,13 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "orders JOIN users ON users.id = orders.user_id" , use_default_dialect=True ) - - - + + + def test_backwards_join(self): # a more controversial feature. join from # User->Address, but the onclause is Address.user. - + sess = create_session() eq_( @@ -612,7 +612,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): sess.query(User, Address).join(Address.user).filter(Address.email_address=='ed@wood.com').all(), [(User(id=8,name=u'ed'), Address(email_address='ed@wood.com'))] ) - + # this was the controversial part. now, raise an error if the feature is abused. # before the error raise was added, this would silently work..... assert_raises( @@ -626,10 +626,10 @@ class JoinTest(QueryTest, AssertsCompiledSQL): sa_exc.InvalidRequestError, sess.query(User).join, adalias, Address.user, ) - + def test_multiple_with_aliases(self): sess = create_session() - + ualias = aliased(User) oalias1 = aliased(Order) oalias2 = aliased(Order) @@ -645,7 +645,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): def test_select_from_orm_joins(self): sess = create_session() - + ualias = aliased(User) oalias1 = aliased(Order) oalias2 = aliased(Order) @@ -702,18 +702,18 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "users_1_name FROM users AS users_1 JOIN orders AS orders_1 ON users_1.id = orders_1.user_id, " "users JOIN orders AS orders_2 ON users.id = orders_2.user_id " "WHERE orders_1.user_id = :user_id_1 OR orders_2.user_id = :user_id_2", - + use_default_dialect=True ) - - + + def test_overlapping_backwards_joins(self): sess = create_session() oalias1 = aliased(Order) oalias2 = aliased(Order) - - # this is invalid SQL - joins from orders_1/orders_2 to User twice. + + # this is invalid SQL - joins from orders_1/orders_2 to User twice. # but that is what was asked for so they get it ! self.assert_compile( sess.query(User).join(oalias1.user).join(oalias2.user), @@ -724,9 +724,9 @@ class JoinTest(QueryTest, AssertsCompiledSQL): def test_replace_multiple_from_clause(self): """test adding joins onto multiple FROM clauses""" - + sess = create_session() - + self.assert_compile( sess.query(Address, User).join(Address.dingaling).join(User.orders, Order.items), "SELECT addresses.id AS addresses_id, addresses.user_id AS addresses_user_id, " @@ -736,7 +736,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "ON orders.id = order_items_1.order_id JOIN items ON items.id = order_items_1.item_id", use_default_dialect = True ) - + def test_multiple_adaption(self): sess = create_session() @@ -747,7 +747,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "JOIN items AS items_1 ON items_1.id = order_items_1.item_id WHERE orders_1.id = :id_1 AND items_1.id = :id_2", use_default_dialect=True ) - + def test_onclause_conditional_adaption(self): sess = create_session() @@ -764,8 +764,8 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "ON orders_1.id = order_items.order_id AND order_items.item_id = items_1.id", use_default_dialect=True ) - - + + oalias = orders.select() self.assert_compile( sess.query(User).join(oalias, User.orders). @@ -779,21 +779,21 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "ON anon_1.id = order_items.order_id AND order_items.item_id = items.id", use_default_dialect=True ) - + # query.join(<stuff>, aliased=True).join(target, sql_expression) # or: query.join(path_to_some_joined_table_mapper).join(target, sql_expression) - + def test_pure_expression_error(self): sess = create_session() - + assert_raises_message(sa.exc.InvalidRequestError, "Could not find a FROM clause to join from", sess.query(users).join, addresses) - - + + def test_orderby_arg_bug(self): sess = create_session() # no arg error result = sess.query(User).join('orders', aliased=True).order_by(Order.id).reset_joinpoint().order_by(users.c.id).all() - + def test_no_onclause(self): sess = create_session() @@ -812,7 +812,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): .filter(Item.description == 'item 4').all(), [User(name='jack')] ) - + def test_clause_onclause(self): sess = create_session() @@ -860,8 +860,8 @@ class JoinTest(QueryTest, AssertsCompiledSQL): all(), [User(name='fred')] ) - - + + def test_aliased_classes(self): sess = create_session() @@ -903,9 +903,9 @@ class JoinTest(QueryTest, AssertsCompiledSQL): def test_expression_onclauses(self): sess = create_session() - + subq = sess.query(User).subquery() - + self.assert_compile( sess.query(User).join(subq, User.name==subq.c.name), "SELECT users.id AS users_id, users.name AS users_name " @@ -913,8 +913,8 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "AS name FROM users) AS anon_1 ON users.name = anon_1.name", use_default_dialect=True ) - - + + subq = sess.query(Order).subquery() self.assert_compile( sess.query(User).join(subq, User.id==subq.c.user_id), @@ -925,15 +925,15 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "anon_1 ON users.id = anon_1.user_id", use_default_dialect=True ) - + self.assert_compile( sess.query(User).join(Order, User.id==Order.user_id), "SELECT users.id AS users_id, users.name AS users_name " "FROM users JOIN orders ON users.id = orders.user_id", use_default_dialect=True ) - - + + def test_implicit_joins_from_aliases(self): sess = create_session() OrderAlias = aliased(Order) @@ -947,7 +947,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): Order(address_id=1,description=u'order 3',isopen=1,user_id=7,id=3) ] ) - + eq_( sess.query(User, OrderAlias, Item.description). join(OrderAlias, 'orders'). @@ -959,11 +959,11 @@ class JoinTest(QueryTest, AssertsCompiledSQL): (User(name=u'jack',id=7), Order(address_id=1,description=u'order 3',isopen=1,user_id=7,id=3), u'item 3'), (User(name=u'fred',id=9), Order(address_id=4,description=u'order 2',isopen=0,user_id=9,id=2), u'item 3') ] - ) - + ) + def test_aliased_classes_m2m(self): sess = create_session() - + (order1, order2, order3, order4, order5) = sess.query(Order).all() (item1, item2, item3, item4, item5) = sess.query(Item).all() expected = [ @@ -980,7 +980,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): (order4, item5), (order5, item5), ] - + q = sess.query(Order) q = q.add_entity(Item).select_from(join(Order, Item, 'items')).order_by(Order.id, Item.id) l = q.all() @@ -996,7 +996,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): (order3, item3), ] ) - + def test_joins_from_adapted_entities(self): # test for #1853 @@ -1034,7 +1034,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): '(SELECT users.id AS id FROM users) AS ' 'anon_2 ON anon_2.id = anon_1.users_id', use_default_dialect=True) - + def test_reset_joinpoint(self): for aliased in (True, False): # load a user who has an order that contains item id 3 and address id 1 (order 3, owned by jack) @@ -1043,7 +1043,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): result = create_session().query(User).outerjoin('orders', 'items', aliased=aliased).filter_by(id=3).reset_joinpoint().outerjoin('orders','address', aliased=aliased).filter_by(id=1).all() assert [User(id=7, name='jack')] == result - + def test_overlap_with_aliases(self): oalias = orders.alias('oalias') @@ -1083,7 +1083,7 @@ class JoinTest(QueryTest, AssertsCompiledSQL): # the left half of the join condition of the any() is aliased. q = sess.query(User).join('orders', aliased=True).filter(Order.items.any(Item.description=='item 4')) assert [User(id=7)] == q.all() - + # test that aliasing gets reset when join() is called q = sess.query(User).join('orders', aliased=True).filter(Order.description=="order 3").join('orders', aliased=True).filter(Order.description=="order 5") assert q.count() == 1 @@ -1106,35 +1106,35 @@ class JoinTest(QueryTest, AssertsCompiledSQL): ) def test_plain_table(self): - + sess = create_session() - + eq_( sess.query(User.name).join(addresses, User.id==addresses.c.user_id).order_by(User.id).all(), [(u'jack',), (u'ed',), (u'ed',), (u'ed',), (u'fred',)] ) - + def test_no_joinpoint_expr(self): sess = create_session() - + # these are consistent regardless of # select_from() being present. - + assert_raises_message( sa_exc.InvalidRequestError, "Could not find a FROM", sess.query(users.c.id).join, User ) - + assert_raises_message( sa_exc.InvalidRequestError, "Could not find a FROM", sess.query(users.c.id).select_from(users).join, User ) - + def test_select_from(self): """Test that the left edge of the join can be set reliably with select_from().""" - + sess = create_session() self.assert_compile( sess.query(Item.id).select_from(User).join(User.orders).join(Order.items), @@ -1152,16 +1152,16 @@ class JoinTest(QueryTest, AssertsCompiledSQL): "SELECT items.id AS items_id FROM users JOIN items ON users.id = items.id", use_default_dialect=True ) - - - - + + + + def test_from_self_resets_joinpaths(self): """test a join from from_self() doesn't confuse joins inside the subquery with the outside. """ sess = create_session() - + self.assert_compile( sess.query(Item).join(Item.keywords).from_self(Keyword).join(Item.keywords), "SELECT keywords.id AS keywords_id, keywords.name AS keywords_name FROM " @@ -1222,30 +1222,30 @@ class MultiplePathTest(_base.MappedTest, AssertsCompiledSQL): class SelfRefMixedTest(_base.MappedTest, AssertsCompiledSQL): run_setup_mappers = 'once' __dialect__ = default.DefaultDialect() - + @classmethod def define_tables(cls, metadata): nodes = Table('nodes', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('parent_id', Integer, ForeignKey('nodes.id')) ) - + sub_table = Table('sub_table', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('node_id', Integer, ForeignKey('nodes.id')), ) - + assoc_table = Table('assoc_table', metadata, Column('left_id', Integer, ForeignKey('nodes.id')), Column('right_id', Integer, ForeignKey('nodes.id')) ) - + @classmethod @testing.resolve_artifact_names def setup_classes(cls): class Node(Base): pass - + class Sub(Base): pass @@ -1272,7 +1272,7 @@ class SelfRefMixedTest(_base.MappedTest, AssertsCompiledSQL): "FROM nodes JOIN nodes AS nodes_1 ON nodes.id = nodes_1.parent_id " "JOIN sub_table ON nodes_1.id = sub_table.node_id" ) - + self.assert_compile( sess.query(Node).join(n1, Node.children).join(Sub, Node.subs), "SELECT nodes.id AS nodes_id, nodes.parent_id AS nodes_parent_id " @@ -1292,7 +1292,7 @@ class SelfRefMixedTest(_base.MappedTest, AssertsCompiledSQL): "assoc_table_1.left_id JOIN nodes AS nodes_1 ON nodes_1.id = " "assoc_table_1.right_id JOIN sub_table ON nodes_1.id = sub_table.node_id", ) - + self.assert_compile( sess.query(Node).join(n1, Node.assoc).join(Sub, Node.subs), "SELECT nodes.id AS nodes_id, nodes.parent_id AS nodes_parent_id " @@ -1300,8 +1300,8 @@ class SelfRefMixedTest(_base.MappedTest, AssertsCompiledSQL): "assoc_table_1.left_id JOIN nodes AS nodes_1 ON nodes_1.id = " "assoc_table_1.right_id JOIN sub_table ON nodes.id = sub_table.node_id", ) - - + + class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): run_setup_mappers = 'once' run_inserts = 'once' @@ -1314,17 +1314,17 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('parent_id', Integer, ForeignKey('nodes.id')), Column('data', String(30))) - + @classmethod def insert_data(cls): # TODO: somehow using setup_classes() # here normally is screwing up the other tests. - + global Node, Sub class Node(Base): def append(self, node): self.children.append(node) - + mapper(Node, nodes, properties={ 'children':relationship(Node, lazy='select', join_depth=3, backref=backref('parent', remote_side=[nodes.c.id]) @@ -1342,7 +1342,7 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): sess.add(n1) sess.flush() sess.close() - + @testing.resolve_artifact_names def test_join(self): sess = create_session() @@ -1353,24 +1353,24 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): ret = sess.query(Node.data).join(Node.children, aliased=True).filter_by(data='n122').all() assert ret == [('n12',)] - + node = sess.query(Node).join('children', 'children', aliased=True).filter_by(data='n122').first() assert node.data=='n1' node = sess.query(Node).filter_by(data='n122').join('parent', aliased=True).filter_by(data='n12').\ join('parent', aliased=True, from_joinpoint=True).filter_by(data='n1').first() assert node.data == 'n122' - + @testing.resolve_artifact_names def test_string_or_prop_aliased(self): """test that join('foo') behaves the same as join(Cls.foo) in a self referential scenario. - + """ - + sess = create_session() nalias = aliased(Node, sess.query(Node).filter_by(data='n1').subquery()) - + q1 = sess.query(nalias).join(nalias.children, aliased=True).\ join(Node.children, from_joinpoint=True) @@ -1388,7 +1388,7 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): "nodes_1.parent_id JOIN nodes ON nodes_1.id = nodes.parent_id", use_default_dialect=True ) - + q1 = sess.query(Node).join(nalias.children, aliased=True).\ join(Node.children, aliased=True, from_joinpoint=True).\ join(Node.children, from_joinpoint=True) @@ -1396,7 +1396,7 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): q2 = sess.query(Node).join(nalias.children, aliased=True).\ join("children", aliased=True, from_joinpoint=True).\ join("children", from_joinpoint=True) - + for q in (q1, q2): self.assert_compile( q, @@ -1409,16 +1409,16 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): "JOIN nodes ON nodes_2.id = nodes.parent_id", use_default_dialect=True ) - + @testing.resolve_artifact_names def test_from_self_inside_excludes_outside(self): """test the propagation of aliased() from inside to outside on a from_self().. """ sess = create_session() - + n1 = aliased(Node) - + # n1 is not inside the from_self(), so all cols must be maintained # on the outside self.assert_compile( @@ -1438,7 +1438,7 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): join(grandparent, parent.parent).\ filter(Node.data=='n122').filter(parent.data=='n12').\ filter(grandparent.data=='n1').from_self().limit(1) - + # parent, grandparent *are* inside the from_self(), so they # should get aliased to the outside. self.assert_compile( @@ -1465,14 +1465,14 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): {'param_1':1}, use_default_dialect=True ) - + @testing.resolve_artifact_names def test_explicit_join(self): sess = create_session() - + n1 = aliased(Node) n2 = aliased(Node) - + self.assert_compile( join(Node, n1, 'children').join(n2, 'children'), "nodes JOIN nodes AS nodes_1 ON nodes.id = nodes_1.parent_id JOIN nodes AS nodes_2 ON nodes_1.id = nodes_2.parent_id", @@ -1500,7 +1500,7 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): "JOIN nodes AS nodes_2 ON nodes_1.id = nodes_2.parent_id", use_default_dialect=True ) - + self.assert_compile( sess.query(Node).join(n1, Node.children).join(n2, Node.children), "SELECT nodes.id AS nodes_id, nodes.parent_id AS nodes_parent_id, nodes.data AS " @@ -1508,14 +1508,14 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): "JOIN nodes AS nodes_2 ON nodes.id = nodes_2.parent_id", use_default_dialect=True ) - + node = sess.query(Node).select_from(join(Node, n1, 'children')).filter(n1.data=='n122').first() assert node.data=='n12' - + node = sess.query(Node).select_from(join(Node, n1, 'children').join(n2, 'children')).\ filter(n2.data=='n122').first() assert node.data=='n1' - + # mix explicit and named onclauses node = sess.query(Node).select_from(join(Node, n1, Node.id==n1.parent_id).join(n2, 'children')).\ filter(n2.data=='n122').first() @@ -1529,11 +1529,11 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): list(sess.query(Node).select_from(join(Node, n1, 'parent').join(n2, 'parent')).\ filter(and_(Node.data=='n122', n1.data=='n12', n2.data=='n1')).values(Node.data, n1.data, n2.data)), [('n122', 'n12', 'n1')]) - + @testing.resolve_artifact_names def test_join_to_nonaliased(self): sess = create_session() - + n1 = aliased(Node) # using 'n1.parent' implicitly joins to unaliased Node @@ -1541,18 +1541,18 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): sess.query(n1).join(n1.parent).filter(Node.data=='n1').all(), [Node(parent_id=1,data=u'n11',id=2), Node(parent_id=1,data=u'n12',id=3), Node(parent_id=1,data=u'n13',id=4)] ) - + # explicit (new syntax) eq_( sess.query(n1).join(Node, n1.parent).filter(Node.data=='n1').all(), [Node(parent_id=1,data=u'n11',id=2), Node(parent_id=1,data=u'n12',id=3), Node(parent_id=1,data=u'n13',id=4)] ) - - + + @testing.resolve_artifact_names def test_multiple_explicit_entities(self): sess = create_session() - + parent = aliased(Node) grandparent = aliased(Node) eq_( @@ -1602,8 +1602,8 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): options(joinedload(Node.children)).first(), (Node(data='n122'), Node(data='n12'), Node(data='n1')) ) - - + + @testing.resolve_artifact_names def test_any(self): sess = create_session() @@ -1615,7 +1615,7 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): @testing.resolve_artifact_names def test_has(self): sess = create_session() - + eq_(sess.query(Node).filter(Node.parent.has(Node.data=='n12')).order_by(Node.id).all(), [Node(data='n121'),Node(data='n122'),Node(data='n123')]) eq_(sess.query(Node).filter(Node.parent.has(Node.data=='n122')).all(), []) @@ -1624,7 +1624,7 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): @testing.resolve_artifact_names def test_contains(self): sess = create_session() - + n122 = sess.query(Node).filter(Node.data=='n122').one() eq_(sess.query(Node).filter(Node.children.contains(n122)).all(), [Node(data='n12')]) @@ -1634,10 +1634,10 @@ class SelfReferentialTest(_base.MappedTest, AssertsCompiledSQL): @testing.resolve_artifact_names def test_eq_ne(self): sess = create_session() - + n12 = sess.query(Node).filter(Node.data=='n12').one() eq_(sess.query(Node).filter(Node.parent==n12).all(), [Node(data='n121'),Node(data='n122'),Node(data='n123')]) - + eq_(sess.query(Node).filter(Node.parent != n12).all(), [Node(data='n1'), Node(data='n11'), Node(data='n12'), Node(data='n13')]) class SelfReferentialM2MTest(_base.MappedTest): @@ -1651,7 +1651,7 @@ class SelfReferentialM2MTest(_base.MappedTest): nodes = Table('nodes', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('data', String(30))) - + node_to_nodes =Table('node_to_nodes', metadata, Column('left_node_id', Integer, ForeignKey('nodes.id'),primary_key=True), Column('right_node_id', Integer, ForeignKey('nodes.id'),primary_key=True), @@ -1660,7 +1660,7 @@ class SelfReferentialM2MTest(_base.MappedTest): @classmethod def insert_data(cls): global Node - + class Node(Base): pass @@ -1678,7 +1678,7 @@ class SelfReferentialM2MTest(_base.MappedTest): n5 = Node(data='n5') n6 = Node(data='n6') n7 = Node(data='n7') - + n1.children = [n2, n3, n4] n2.children = [n3, n6, n7] n3.children = [n5, n4] @@ -1703,7 +1703,7 @@ class SelfReferentialM2MTest(_base.MappedTest): def test_explicit_join(self): sess = create_session() - + n1 = aliased(Node) eq_( sess.query(Node).select_from(join(Node, n1, 'children')).filter(n1.data.in_(['n3', 'n7'])).order_by(Node.id).all(), diff --git a/test/orm/test_lazy_relations.py b/test/orm/test_lazy_relations.py index 1bf7eecaf..3208d060e 100644 --- a/test/orm/test_lazy_relations.py +++ b/test/orm/test_lazy_relations.py @@ -191,7 +191,7 @@ class LazyTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_many_to_one_binds(self): mapper(Address, addresses, primary_key=[addresses.c.user_id, addresses.c.email_address]) - + mapper(User, users, properties = dict( address = relationship(Address, uselist=False, primaryjoin=sa.and_(users.c.id==addresses.c.user_id, addresses.c.email_address=='ed@bettyboop.com') @@ -207,7 +207,7 @@ class LazyTest(_fixtures.FixtureTest): ], list(q) ) - + @testing.resolve_artifact_names def test_double(self): @@ -217,9 +217,9 @@ class LazyTest(_fixtures.FixtureTest): closedorders = sa.alias(orders, 'closedorders') mapper(Address, addresses) - + mapper(Order, orders) - + open_mapper = mapper(Order, openorders, non_primary=True) closed_mapper = mapper(Order, closedorders, non_primary=True) mapper(User, users, properties = dict( @@ -306,10 +306,10 @@ class LazyTest(_fixtures.FixtureTest): class SmallintDecorator(TypeDecorator): impl = SmallInteger - + class SomeDBInteger(sa.Integer): pass - + for tt in [ Integer, SmallInteger, diff --git a/test/orm/test_legacy_mutable.py b/test/orm/test_legacy_mutable.py index f3d3d583d..dee3f193c 100644 --- a/test/orm/test_legacy_mutable.py +++ b/test/orm/test_legacy_mutable.py @@ -40,7 +40,7 @@ class MutableTypesTest(_base.MappedTest): @testing.resolve_artifact_names def test_modified_status(self): f1 = Foo(data = pickleable.Bar(4,5)) - + session = Session() session.add(f1) session.commit() @@ -52,27 +52,27 @@ class MutableTypesTest(_base.MappedTest): f2.data.y = 19 assert f2 in session.dirty assert 'data' not in sa.orm.attributes.instance_state(f2).unmodified - + @testing.resolve_artifact_names def test_mutations_persisted(self): f1 = Foo(data = pickleable.Bar(4,5)) - + session = Session() session.add(f1) session.commit() f1.data session.close() - + f2 = session.query(Foo).first() f2.data.y = 19 session.commit() f2.data session.close() - + f3 = session.query(Foo).first() ne_(f3.data,f1.data) eq_(f3.data, pickleable.Bar(4, 19)) - + @testing.resolve_artifact_names def test_no_unnecessary_update(self): f1 = Foo(data = pickleable.Bar(4,5), val = u'hi') @@ -82,7 +82,7 @@ class MutableTypesTest(_base.MappedTest): session.commit() self.sql_count_(0, session.commit) - + f1.val = u'someothervalue' self.assert_sql(testing.db, session.commit, [ ("UPDATE mutable_t SET val=:val " @@ -95,7 +95,7 @@ class MutableTypesTest(_base.MappedTest): ("UPDATE mutable_t SET data=:data, val=:val " "WHERE mutable_t.id = :mutable_t_id", {'mutable_t_id': f1.id, 'val': u'hi', 'data':f1.data})]) - + @testing.resolve_artifact_names def test_mutated_state_resurrected(self): f1 = Foo(data = pickleable.Bar(4,5), val = u'hi') @@ -119,7 +119,7 @@ class MutableTypesTest(_base.MappedTest): """test that a non-mutable attribute event subsequent to a mutable event prevents the object from falling into resurrected state. - + """ f1 = Foo(data = pickleable.Bar(4, 5), val=u'some val') session = Session() @@ -130,7 +130,7 @@ class MutableTypesTest(_base.MappedTest): f1.val=u'some new val' assert sa.orm.attributes.instance_state(f1)._strong_obj is not None - + del f1 session.commit() eq_( @@ -141,11 +141,11 @@ class MutableTypesTest(_base.MappedTest): @testing.resolve_artifact_names def test_non_mutated_state_not_resurrected(self): f1 = Foo(data = pickleable.Bar(4,5)) - + session = Session() session.add(f1) session.commit() - + session = Session() f1 = session.query(Foo).first() del f1 @@ -159,7 +159,7 @@ class MutableTypesTest(_base.MappedTest): def test_scalar_no_net_change_no_update(self): """Test that a no-net-change on a scalar attribute event doesn't cause an UPDATE for a mutable state. - + """ f1 = Foo(val=u'hi') @@ -177,45 +177,45 @@ class MutableTypesTest(_base.MappedTest): def test_expire_attribute_set(self): """test no SELECT emitted when assigning to an expired mutable attribute. - + """ - + f1 = Foo(data = pickleable.Bar(4, 5), val=u'some val') session = Session() session.add(f1) session.commit() - + assert 'data' not in f1.__dict__ def go(): f1.data = pickleable.Bar(10, 15) self.sql_count_(0, go) session.commit() - + eq_(f1.data.x, 10) @testing.resolve_artifact_names def test_expire_mutate(self): """test mutations are detected on an expired mutable attribute.""" - + f1 = Foo(data = pickleable.Bar(4, 5), val=u'some val') session = Session() session.add(f1) session.commit() - + assert 'data' not in f1.__dict__ def go(): f1.data.x = 10 self.sql_count_(1, go) session.commit() - + eq_(f1.data.x, 10) - + @testing.resolve_artifact_names def test_deferred_attribute_set(self): """test no SELECT emitted when assigning to a deferred mutable attribute. - + """ sa.orm.clear_mappers() mapper(Foo, mutable_t, properties={ @@ -226,22 +226,22 @@ class MutableTypesTest(_base.MappedTest): session = Session() session.add(f1) session.commit() - + session.close() - + f1 = session.query(Foo).first() def go(): f1.data = pickleable.Bar(10, 15) self.sql_count_(0, go) session.commit() - + eq_(f1.data.x, 10) @testing.resolve_artifact_names def test_deferred_mutate(self): """test mutations are detected on a deferred mutable attribute.""" - + sa.orm.clear_mappers() mapper(Foo, mutable_t, properties={ 'data':sa.orm.deferred(mutable_t.c.data) @@ -251,15 +251,15 @@ class MutableTypesTest(_base.MappedTest): session = Session() session.add(f1) session.commit() - + session.close() - + f1 = session.query(Foo).first() def go(): f1.data.x = 10 self.sql_count_(1, go) session.commit() - + def go(): eq_(f1.data.x, 10) self.sql_count_(1, go) diff --git a/test/orm/test_load_on_fks.py b/test/orm/test_load_on_fks.py index 3e7ddb8c2..f8a080f3f 100644 --- a/test/orm/test_load_on_fks.py +++ b/test/orm/test_load_on_fks.py @@ -15,19 +15,19 @@ class FlushOnPendingTest(AssertsExecutionResults, TestBase): def setUp(self): global Parent, Child, Base Base= declarative_base() - + class Parent(Base): __tablename__ = 'parent' - + id= Column(Integer, primary_key=True, test_needs_autoincrement=True) name = Column(String(50), nullable=False) children = relationship("Child", load_on_pending=True) - + class Child(Base): __tablename__ = 'child' id= Column(Integer, primary_key=True, test_needs_autoincrement=True) parent_id = Column(Integer, ForeignKey('parent.id')) - + Base.metadata.create_all(engine) def tearDown(self): @@ -35,38 +35,38 @@ class FlushOnPendingTest(AssertsExecutionResults, TestBase): def test_annoying_autoflush_one(self): sess = Session(engine) - + p1 = Parent() sess.add(p1) p1.children = [] def test_annoying_autoflush_two(self): sess = Session(engine) - + p1 = Parent() sess.add(p1) assert p1.children == [] def test_dont_load_if_no_keys(self): sess = Session(engine) - + p1 = Parent() sess.add(p1) - + def go(): assert p1.children == [] self.assert_sql_count(testing.db, go, 0) class LoadOnFKsTest(AssertsExecutionResults, TestBase): - + def setUp(self): global Parent, Child, Base Base= declarative_base() - + class Parent(Base): __tablename__ = 'parent' __table_args__ = {'mysql_engine':'InnoDB'} - + id= Column(Integer, primary_key=True, test_needs_autoincrement=True) class Child(Base): @@ -75,9 +75,9 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): id= Column(Integer, primary_key=True, test_needs_autoincrement=True) parent_id = Column(Integer, ForeignKey('parent.id')) - + parent = relationship(Parent, backref=backref("children")) - + Base.metadata.create_all(engine) global sess, p1, p2, c1, c2 @@ -91,7 +91,7 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): assert c1 in sess sess.commit() - + def tearDown(self): sess.rollback() Base.metadata.drop_all(engine) @@ -103,7 +103,7 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): sess.add(c3) c3.parent_id = p1.id c3.parent = p1 - + # a side effect of load-on-pending with no autoflush. # a change to the backref event handler to check # collection membership before assuming "old == new so return" @@ -117,27 +117,27 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): sess.add(c3) c3.parent_id = p1.id c3.parent = p1 - + assert c3 in p1.children def test_no_load_on_pending_allows_backref_event(self): # users who stick with the program and don't use # 'load_on_pending' get expected behavior - + sess.autoflush = False c3 = Child() sess.add(c3) c3.parent_id = p1.id c3.parent = p1 - + assert c3 in p1.children - + def test_autoflush_on_pending(self): c3 = Child() sess.add(c3) c3.parent_id = p1.id - + # pendings don't autoflush assert c3.parent is None @@ -146,10 +146,10 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): c3 = Child() sess.add(c3) c3.parent_id = p1.id - + # ...unless the flag is on assert c3.parent is p1 - + def test_load_on_pending_with_set(self): Child.parent.property.load_on_pending = True @@ -157,13 +157,13 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): c3 = Child() sess.add(c3) - + c3.parent_id = p1.id def go(): c3.parent = p1 self.assert_sql_count(testing.db, go, 0) - + def test_backref_doesnt_double(self): Child.parent.property.load_on_pending = True sess.autoflush = False @@ -175,12 +175,12 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): c3.parent = p1 c3.parent = p1 assert len(p1.children)== 2 - + def test_m2o_lazy_loader_on_persistent(self): """Compare the behaviors from the lazyloader using the "committed" state in all cases, vs. the lazyloader using the "current" state in all cases except during flush. - + """ for loadfk in (True, False): for loadrel in (True, False): @@ -188,23 +188,23 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): for manualflush in (True, False): for fake_autoexpire in (True, False): sess.autoflush = autoflush - + if loadfk: c1.parent_id if loadrel: c1.parent c1.parent_id = p2.id - + if manualflush: sess.flush() - + # fake_autoexpire refers to the eventual # auto-expire of 'parent' when c1.parent_id # is altered. if fake_autoexpire: sess.expire(c1, ['parent']) - + # old 0.6 behavior #if manualflush and (not loadrel or fake_autoexpire): # # a flush occurs, we get p2 @@ -219,15 +219,15 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): # # if things were loaded, autoflush doesn't even # # happen. # assert c1.parent is p1 - + # new behavior if loadrel and not fake_autoexpire: assert c1.parent is p1 else: assert c1.parent is p2 - + sess.rollback() - + def test_m2o_lazy_loader_on_pending(self): for loadonpending in (False, True): for autoflush in (False, True): @@ -237,15 +237,15 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): c2 = Child() sess.add(c2) c2.parent_id = p2.id - + if manualflush: sess.flush() - + if loadonpending or manualflush: assert c2.parent is p2 else: assert c2.parent is None - + sess.rollback() def test_m2o_lazy_loader_on_transient(self): @@ -256,18 +256,18 @@ class LoadOnFKsTest(AssertsExecutionResults, TestBase): Child.parent.property.load_on_pending = loadonpending sess.autoflush = autoflush c2 = Child() - + if attach: sess._attach(instance_state(c2)) c2.parent_id = p2.id - + if manualflush: sess.flush() - + if loadonpending and attach: assert c2.parent is p2 else: assert c2.parent is None - + sess.rollback() diff --git a/test/orm/test_manytomany.py b/test/orm/test_manytomany.py index 0e7a6e40f..9764ed684 100644 --- a/test/orm/test_manytomany.py +++ b/test/orm/test_manytomany.py @@ -165,11 +165,11 @@ class M2MTest(_base.MappedTest): sess.add_all([p1, p2]) p1.parent_places.append(p2) sess.flush() - + sess.expire_all() assert p1 in p2.parent_places assert p2 in p1.parent_places - + @testing.resolve_artifact_names def test_double(self): @@ -241,7 +241,7 @@ class M2MTest(_base.MappedTest): passive_updates=False) }) mapper(Transition, transition) - + p1 = Place('place1') t1 = Transition('t1') p1.transitions.append(t1) @@ -251,10 +251,10 @@ class M2MTest(_base.MappedTest): p1.place_id p1.transitions - + sess.execute("delete from place_input", mapper=Place) p1.place_id = 7 - + assert_raises_message( orm_exc.StaleDataError, r"UPDATE statement on table 'place_input' expected to " @@ -262,7 +262,7 @@ class M2MTest(_base.MappedTest): sess.commit ) sess.rollback() - + p1.place_id p1.transitions sess.execute("delete from place_input", mapper=Place) @@ -273,7 +273,7 @@ class M2MTest(_base.MappedTest): r"delete 1 row\(s\); Only 0 were matched.", sess.commit ) - + class M2MTest2(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -327,7 +327,7 @@ class M2MTest2(_base.MappedTest): @testing.resolve_artifact_names def test_dupliates_raise(self): """test constraint error is raised for dupe entries in a list""" - + mapper(Student, student) mapper(Course, course, properties={ 'students': relationship(Student, enroll, backref='courses')}) @@ -339,7 +339,7 @@ class M2MTest2(_base.MappedTest): s1.courses.append(c1) sess.add(s1) assert_raises(sa.exc.DBAPIError, sess.flush) - + @testing.resolve_artifact_names def test_delete(self): """A many-to-many table gets cleared out with deletion from the backref side""" @@ -406,7 +406,7 @@ class M2MTest3(_base.MappedTest): 'a2s': relationship(A, secondary=c2a2, lazy='joined')}) assert create_session().query(C).with_labels().statement is not None - + # TODO: seems like just a test for an ancient exception throw. # how about some data/inserts/queries/assertions for this one @@ -427,7 +427,7 @@ class M2MTest4(_base.MappedTest): Column('t1', Integer, ForeignKey('table1.col1')), Column('t2', Integer, ForeignKey('table2.col1')), ) - + @testing.resolve_artifact_names def test_delete_parent(self): class A(_base.ComparableEntity): diff --git a/test/orm/test_mapper.py b/test/orm/test_mapper.py index 54613c222..2cc180895 100644 --- a/test/orm/test_mapper.py +++ b/test/orm/test_mapper.py @@ -31,7 +31,7 @@ class MapperTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_update_attr_keys(self): """test that update()/insert() use the correct key when given InstrumentedAttributes.""" - + mapper(User, users, properties={ 'foobar':users.c.name }) @@ -41,11 +41,11 @@ class MapperTest(_fixtures.FixtureTest): users.update().values({User.foobar:User.foobar + 'foo'}).execute() eq_(sa.select([User.foobar]).where(User.foobar=='name1foo').execute().fetchall(), [('name1foo',)]) - + @testing.resolve_artifact_names def test_utils(self): from sqlalchemy.orm.util import _is_mapped_class, _is_aliased_class - + class Foo(object): x = "something" @property @@ -53,7 +53,7 @@ class MapperTest(_fixtures.FixtureTest): return "somethign else" m = mapper(Foo, users) a1 = aliased(Foo) - + f = Foo() for fn, arg, ret in [ @@ -93,13 +93,13 @@ class MapperTest(_fixtures.FixtureTest): """test preservation of mapper compile errors raised during hasattr(), as well as for redundant mapper compile calls. Test that repeated calls don't stack up error messages. - + """ - + mapper(Address, addresses, properties={ 'user':relationship(User) }) - + hasattr(Address.user, 'property') for i in range(3): assert_raises_message(sa.exc.InvalidRequestError, @@ -109,7 +109,7 @@ class MapperTest(_fixtures.FixtureTest): "Original exception was: Class " "'test.orm._fixtures.User' is not mapped$" , configure_mappers) - + @testing.resolve_artifact_names def test_column_prefix(self): mapper(User, users, column_prefix='_', properties={ @@ -175,7 +175,7 @@ class MapperTest(_fixtures.FixtureTest): "not represented in the mapper's table", mapper, User, users, properties={'foo' : addresses.c.user_id}) - + @testing.resolve_artifact_names def test_constructor_exc(self): """TypeError is raised for illegal constructor args, @@ -248,12 +248,12 @@ class MapperTest(_fixtures.FixtureTest): m= mapper(User, users) assert not m.configured configure_mappers() - + m2 = mapper(Address, addresses, properties={ 'user':relationship(User, backref='addresses') }) assert m.get_property('addresses') - + @testing.resolve_artifact_names def test_add_property(self): assert_col = [] @@ -279,7 +279,7 @@ class MapperTest(_fixtures.FixtureTest): class UCComparator(sa.orm.PropComparator): __hash__ = None - + def __eq__(self, other): cls = self.prop.parent.class_ col = getattr(cls, 'name') @@ -452,7 +452,7 @@ class MapperTest(_fixtures.FixtureTest): def name(self): pass class Empty(object):pass - + empty = mapper(Empty, t, properties={'empty_id' : t.c.id}, include_properties=[]) p_m = mapper(Person, t, polymorphic_on=t.c.type, @@ -473,12 +473,12 @@ class MapperTest(_fixtures.FixtureTest): column_prefix="p_") hd_m = mapper(HasDef, t, column_prefix="h_") - + fb_m = mapper(Fub, t, include_properties=(t.c.id, t.c.type)) frb_m = mapper(Frob, t, column_prefix='f_', exclude_properties=(t.c.boss_id, 'employee_number', t.c.vendor_id)) - + configure_mappers() def assert_props(cls, want): @@ -490,9 +490,9 @@ class MapperTest(_fixtures.FixtureTest): have = set([p.key for p in class_mapper(cls).iterate_properties]) want = set(want) eq_(have, want) - + assert_props(HasDef, ['h_boss_id', 'h_employee_number', 'h_id', - 'name', 'h_name', 'h_vendor_id', 'h_type']) + 'name', 'h_name', 'h_vendor_id', 'h_type']) assert_props(Person, ['id', 'name', 'type']) assert_instrumented(Person, ['id', 'name', 'type']) assert_props(Employee, ['boss', 'boss_id', 'employee_number', @@ -501,10 +501,10 @@ class MapperTest(_fixtures.FixtureTest): 'id', 'name', 'type']) assert_props(Manager, ['boss', 'boss_id', 'employee_number', 'peon', 'id', 'name', 'type']) - + # 'peon' and 'type' are both explicitly stated properties assert_instrumented(Manager, ['peon', 'type', 'id']) - + assert_props(Vendor, ['vendor_id', 'id', 'name', 'type']) assert_props(Hoho, ['id', 'name', 'type']) assert_props(Lala, ['p_employee_number', 'p_id', 'p_name', 'p_type']) @@ -521,11 +521,11 @@ class MapperTest(_fixtures.FixtureTest): Foo, inherits=Person, polymorphic_identity='foo', exclude_properties=('type', ), ) - + @testing.resolve_artifact_names def test_mapping_to_join_raises(self): """Test implicit merging of two cols raises.""" - + usersaddresses = sa.join(users, addresses, users.c.id == addresses.c.user_id) assert_raises_message( @@ -624,12 +624,12 @@ class MapperTest(_fixtures.FixtureTest): m1 = mapper(Item, items, primary_key=[items.c.id]) m2 = mapper(Keyword, keywords, primary_key=keywords.c.id) m3 = mapper(User, users, primary_key=(users.c.id,)) - + assert m1.primary_key[0] is items.c.id assert m2.primary_key[0] is keywords.c.id assert m3.primary_key[0] is users.c.id - - + + @testing.resolve_artifact_names def test_custom_join(self): """select_from totally replace the FROM parameters.""" @@ -668,7 +668,7 @@ class MapperTest(_fixtures.FixtureTest): create_session().query(User).order_by(User.name).all(), [User(id=10, name=u'chuck'), User(id=8, name=u'ed'), User(id=9, name=u'fred'), User(id=7, name=u'jack')] ) - + # 'Raises a "expression evaluation not supported" error at prepare time @testing.fails_on('firebird', 'FIXME: unknown') @testing.resolve_artifact_names @@ -731,14 +731,14 @@ class MapperTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_override_2(self): """exclude_properties cancels the error.""" - + mapper(User, users, exclude_properties=['name'], properties=dict( name=relationship(mapper(Address, addresses)))) - + assert bool(User.name) - + @testing.resolve_artifact_names def test_override_3(self): """The column being named elsewhere also cancels the error,""" @@ -771,7 +771,7 @@ class MapperTest(_fixtures.FixtureTest): adlist = synonym('addresses'), adname = synonym('addresses') )) - + # ensure the synonym can get at the proxied comparators without # an explicit compile User.name == 'ed' @@ -783,16 +783,16 @@ class MapperTest(_fixtures.FixtureTest): # test compile assert not isinstance(User.uname == 'jack', bool) - + assert User.uname.property assert User.adlist.property - + sess = create_session() - + # test RowTuple names row = sess.query(User.id, User.uname).first() assert row.uname == row[1] - + u = sess.query(User).filter(User.uname=='jack').one() fixture = self.static.user_address_result[0].addresses @@ -886,22 +886,22 @@ class MapperTest(_fixtures.FixtureTest): def test_comparable(self): class extendedproperty(property): attribute = 123 - + def method1(self): return "method1" - + def __getitem__(self, key): return 'value' class UCComparator(sa.orm.PropComparator): __hash__ = None - + def method1(self): return "uccmethod1" - + def method2(self, other): return "method2" - + def __eq__(self, other): cls = self.prop.parent.class_ col = getattr(cls, 'name') @@ -940,7 +940,7 @@ class MapperTest(_fixtures.FixtureTest): AttributeError, "Neither 'extendedproperty' object nor 'UCComparator' object has an attribute 'nonexistent'", getattr, User.uc_name, 'nonexistent') - + # test compile assert not isinstance(User.uc_name == 'jack', bool) u = q.filter(User.uc_name=='JACK').one() @@ -973,15 +973,15 @@ class MapperTest(_fixtures.FixtureTest): def __eq__(self, other): # lower case comparison return func.lower(self.__clause_element__()) == func.lower(other) - + def intersects(self, other): # non-standard comparator return self.__clause_element__().op('&=')(other) - + mapper(User, users, properties={ 'name':sa.orm.column_property(users.c.name, comparator_factory=MyComparator) }) - + assert_raises_message( AttributeError, "Neither 'InstrumentedAttribute' object nor 'MyComparator' object has an attribute 'nonexistent'", @@ -989,7 +989,7 @@ class MapperTest(_fixtures.FixtureTest): eq_(str((User.name == 'ed').compile(dialect=sa.engine.default.DefaultDialect())) , "lower(users.name) = lower(:lower_1)") eq_(str((User.name.intersects('ed')).compile(dialect=sa.engine.default.DefaultDialect())), "users.name &= :name_1") - + @testing.resolve_artifact_names def test_reentrant_compile(self): @@ -997,7 +997,7 @@ class MapperTest(_fixtures.FixtureTest): def post_instrument_class(self, mapper): super(MyFakeProperty, self).post_instrument_class(mapper) configure_mappers() - + m1 = mapper(User, users, properties={ 'name':MyFakeProperty(users.c.name) }) @@ -1009,13 +1009,13 @@ class MapperTest(_fixtures.FixtureTest): def post_instrument_class(self, mapper): super(MyFakeProperty, self).post_instrument_class(mapper) configure_mappers() - + m1 = mapper(User, users, properties={ 'name':MyFakeProperty(users.c.name) }) m2 = mapper(Address, addresses) configure_mappers() - + @testing.resolve_artifact_names def test_reconstructor(self): recon = [] @@ -1105,7 +1105,7 @@ class MapperTest(_fixtures.FixtureTest): pass class Sub(Base): pass - + mapper(Base, users) sa.orm.configure_mappers() @@ -1126,14 +1126,14 @@ class MapperTest(_fixtures.FixtureTest): def test_unmapped_subclass_error_premap(self): class Base(object): pass - + mapper(Base, users) - + class Sub(Base): pass sa.orm.configure_mappers() - + # we can create new instances, set attributes. s = Sub() s.name = 'foo' @@ -1142,11 +1142,11 @@ class MapperTest(_fixtures.FixtureTest): attributes.get_history(s, 'name'), (['foo'], (), ()) ) - + # using it with an ORM operation, raises assert_raises(sa.orm.exc.UnmappedClassError, create_session().add, Sub()) - + @testing.resolve_artifact_names def test_oldstyle_mixin(self): class OldStyle: @@ -1165,7 +1165,7 @@ class MapperTest(_fixtures.FixtureTest): mapper(B, users) class DocumentTest(testing.TestBase): - + def test_doc_propagate(self): metadata = MetaData() t1 = Table('t1', metadata, @@ -1183,10 +1183,10 @@ class DocumentTest(testing.TestBase): class Foo(object): pass - + class Bar(object): pass - + mapper(Foo, t1, properties={ 'bars':relationship(Bar, doc="bar relationship", @@ -1205,11 +1205,11 @@ class DocumentTest(testing.TestBase): eq_(Foo.hoho.__doc__, "syn of col4") eq_(Bar.col1.__doc__, "primary key column") eq_(Bar.foo.__doc__, "foo relationship") - - - + + + class OptionsTest(_fixtures.FixtureTest): - + @testing.fails_if(lambda: True, "0.7 regression, may not support " "synonyms for relationship") @testing.fails_on('maxdb', 'FIXME: unknown') @@ -1219,7 +1219,7 @@ class OptionsTest(_fixtures.FixtureTest): addresses = relationship(mapper(Address, addresses), lazy='select', order_by=addresses.c.id), adlist = synonym('addresses'))) - + def go(): sess = create_session() u = (sess.query(User). @@ -1379,9 +1379,9 @@ class OptionsTest(_fixtures.FixtureTest): items = relationship(Item, secondary=order_items) )) mapper(Item, items) - + sess = create_session() - + oalias = aliased(Order) opt1 = sa.orm.joinedload(User.orders, Order.items) opt2a, opt2b = sa.orm.contains_eager(User.orders, Order.items, alias=oalias) @@ -1390,7 +1390,7 @@ class OptionsTest(_fixtures.FixtureTest): assert opt1 in ustate.load_options assert opt2a not in ustate.load_options assert opt2b not in ustate.load_options - + import pickle pickle.dumps(u1) @@ -1424,7 +1424,7 @@ class DeepOptionsTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_deep_options_2(self): """test (joined|subquery)load_all() options""" - + sess = create_session() l = (sess.query(User). @@ -1491,7 +1491,7 @@ class ValidatorTest(_fixtures.FixtureTest): def validate_name(self, key, name): assert name != 'fred' return name + ' modified' - + mapper(User, users) sess = create_session() u1 = User(name='ed') @@ -1502,7 +1502,7 @@ class ValidatorTest(_fixtures.FixtureTest): sess.flush() sess.expunge_all() eq_(sess.query(User).filter_by(name='ed modified').one(), User(name='ed')) - + @testing.resolve_artifact_names def test_collection(self): @@ -1511,7 +1511,7 @@ class ValidatorTest(_fixtures.FixtureTest): def validate_address(self, key, ad): assert '@' in ad.email_address return ad - + mapper(User, users, properties={'addresses':relationship(Address)}) mapper(Address, addresses) sess = create_session() @@ -1532,12 +1532,12 @@ class ComparatorFactoryTest(_fixtures.FixtureTest, AssertsCompiledSQL): class DummyComposite(object): def __init__(self, x, y): pass - + from sqlalchemy.orm.interfaces import PropComparator - + class MyFactory(PropComparator): pass - + for args in ( (column_property, users.c.name), (deferred, users.c.name), @@ -1551,11 +1551,11 @@ class ComparatorFactoryTest(_fixtures.FixtureTest, AssertsCompiledSQL): fn = args[0] args = args[1:] fn(comparator_factory=MyFactory, *args) - + @testing.resolve_artifact_names def test_column(self): from sqlalchemy.orm.properties import ColumnProperty - + class MyFactory(ColumnProperty.Comparator): __hash__ = None def __eq__(self, other): @@ -1581,7 +1581,7 @@ class ComparatorFactoryTest(_fixtures.FixtureTest, AssertsCompiledSQL): User.name == 'ed', "foobar(users.name) = foobar(:foobar_1)", dialect=default.DefaultDialect()) - + self.assert_compile( aliased(User).name == 'ed', "foobar(users_1.name) = foobar(:foobar_1)", @@ -1600,7 +1600,7 @@ class ComparatorFactoryTest(_fixtures.FixtureTest, AssertsCompiledSQL): __hash__ = None def __eq__(self, other): return func.foobar(self.__clause_element__().c.id) == func.foobar(other.user_id) - + mapper(User, users) mapper(Address, addresses, properties={ 'user':relationship(User, comparator_factory=MyFactory, @@ -1614,7 +1614,7 @@ class ComparatorFactoryTest(_fixtures.FixtureTest, AssertsCompiledSQL): self.assert_compile(aliased(Address).user == User(id=5), "foobar(addresses_1.user_id) = foobar(:foobar_1)", dialect=default.DefaultDialect()) self.assert_compile(aliased(User).addresses == Address(id=5, user_id=7), "foobar(users_1.id) = foobar(:foobar_1)", dialect=default.DefaultDialect()) - + class DeferredTest(_fixtures.FixtureTest): @testing.resolve_artifact_names @@ -1664,7 +1664,7 @@ class DeferredTest(_fixtures.FixtureTest): 'isopen':synonym('_isopen', map_column=True), 'description':deferred(orders.c.description, group='foo') }) - + sess = create_session() o1 = sess.query(Order).get(1) eq_(o1.description, "order 1") @@ -1810,7 +1810,7 @@ class DeferredTest(_fixtures.FixtureTest): def go(): q.all()[0].user_id - + self.sql_eq_(go, [ ("SELECT orders.id AS orders_id, " "orders.address_id AS orders_address_id, " @@ -1913,7 +1913,7 @@ class SecondaryOptionsTest(_base.MappedTest): run_inserts = 'once' run_deletes = None - + @classmethod def define_tables(cls, metadata): Table("base", metadata, @@ -1930,7 +1930,7 @@ class SecondaryOptionsTest(_base.MappedTest): Table('related', metadata, Column('id', Integer, ForeignKey('base.id'), primary_key=True), ) - + @classmethod @testing.resolve_artifact_names def setup_mappers(cls): @@ -1950,7 +1950,7 @@ class SecondaryOptionsTest(_base.MappedTest): }) mapper(Child2, child2, inherits=Base, polymorphic_identity='child2') mapper(Related, related) - + @classmethod @testing.resolve_artifact_names def insert_data(cls): @@ -1980,12 +1980,12 @@ class SecondaryOptionsTest(_base.MappedTest): {'id':5}, {'id':6}, ]) - + @testing.resolve_artifact_names def test_contains_eager(self): sess = create_session() - - + + child1s = sess.query(Child1).join(Child1.related).options(sa.orm.contains_eager(Child1.related)).order_by(Child1.id) def go(): @@ -1994,7 +1994,7 @@ class SecondaryOptionsTest(_base.MappedTest): [Child1(id=1, related=Related(id=1)), Child1(id=2, related=Related(id=2)), Child1(id=3, related=Related(id=3))] ) self.assert_sql_count(testing.db, go, 1) - + c1 = child1s[0] self.assert_sql_execution( @@ -2020,7 +2020,7 @@ class SecondaryOptionsTest(_base.MappedTest): [Child1(id=1, related=Related(id=1)), Child1(id=2, related=Related(id=2)), Child1(id=3, related=Related(id=3))] ) self.assert_sql_count(testing.db, go, 1) - + c1 = child1s[0] self.assert_sql_execution( @@ -2050,7 +2050,7 @@ class SecondaryOptionsTest(_base.MappedTest): [Child1(id=1, related=Related(id=1)), Child1(id=2, related=Related(id=2)), Child1(id=3, related=Related(id=3))] ) self.assert_sql_count(testing.db, go, 4) - + c1 = child1s[0] # this *does* joinedload @@ -2064,7 +2064,7 @@ class SecondaryOptionsTest(_base.MappedTest): {'param_1':4} ) ) - + class DeferredPopulationTest(_base.MappedTest): @classmethod @@ -2086,7 +2086,7 @@ class DeferredPopulationTest(_base.MappedTest): mapper(Human, human, properties={"thing": relationship(Thing)}) mapper(Thing, thing, properties={"name": deferred(thing.c.name)}) - + @classmethod @testing.resolve_artifact_names def insert_data(cls): @@ -2097,7 +2097,7 @@ class DeferredPopulationTest(_base.MappedTest): human.insert().execute([ {"id": 1, "thing_id": 1, "name": "Clark Kent"}, ]) - + def _test(self, thing): assert "name" in attributes.instance_state(thing).dict @@ -2121,7 +2121,7 @@ class DeferredPopulationTest(_base.MappedTest): result = session.query(Thing).first() thing = session.query(Thing).options(sa.orm.undefer("name")).first() self._test(thing) - + @testing.resolve_artifact_names def test_joinedload_with_clear(self): session = create_session() @@ -2151,8 +2151,8 @@ class DeferredPopulationTest(_base.MappedTest): result = session.query(Human).add_entity(Thing).join("thing").first() thing = session.query(Thing).options(sa.orm.undefer("name")).first() self._test(thing) - - + + class NoLoadTest(_fixtures.FixtureTest): @@ -2195,8 +2195,8 @@ class NoLoadTest(_fixtures.FixtureTest): ) - - + + class RequirementsTest(_base.MappedTest): """Tests the contract for user classes.""" @@ -2232,14 +2232,14 @@ class RequirementsTest(_base.MappedTest): assert_raises(sa.exc.ArgumentError, mapper, OldStyle, ht1) assert_raises(sa.exc.ArgumentError, mapper, 123) - + class NoWeakrefSupport(str): pass # TODO: is weakref support detectable without an instance? #self.assertRaises(sa.exc.ArgumentError, mapper, NoWeakrefSupport, t2) # end Py2K - + @testing.resolve_artifact_names def test_comparison_overrides(self): """Simple tests to ensure users can supply comparison __methods__. @@ -2340,7 +2340,7 @@ class RequirementsTest(_base.MappedTest): class H1(object): def __len__(self): return len(self.get_value()) - + def get_value(self): self.value = "foobar" return self.value @@ -2352,10 +2352,10 @@ class RequirementsTest(_base.MappedTest): def get_value(self): self.value = "foobar" return self.value - + mapper(H1, ht1) mapper(H2, ht1) - + h1 = H1() h1.value = "Asdf" h1.value = "asdf asdf" # ding @@ -2363,7 +2363,7 @@ class RequirementsTest(_base.MappedTest): h2 = H2() h2.value = "Asdf" h2.value = "asdf asdf" # ding - + class MagicNamesTest(_base.MappedTest): @classmethod @@ -2403,7 +2403,7 @@ class MagicNamesTest(_base.MappedTest): sess.add(c) sess.flush() sess.expunge_all() - + for C, M in ((Cartographer, Map), (sa.orm.aliased(Cartographer), sa.orm.aliased(Map))): c1 = (sess.query(C). diff --git a/test/orm/test_merge.py b/test/orm/test_merge.py index 1eafa59e8..d07efd987 100644 --- a/test/orm/test_merge.py +++ b/test/orm/test_merge.py @@ -53,7 +53,7 @@ class MergeTest(_fixtures.FixtureTest): def go(): sess.merge(u) self.assert_sql_count(testing.db, go, 0) - + @testing.resolve_artifact_names def test_transient_to_pending_collection(self): mapper(User, users, properties={ @@ -241,9 +241,9 @@ class MergeTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_merge_empty_attributes(self): mapper(User, dingalings) - + sess = create_session() - + # merge empty stuff. goes in as NULL. # not sure what this was originally trying to # test. @@ -255,17 +255,17 @@ class MergeTest(_fixtures.FixtureTest): u2 = User(id=2, data="foo") sess.add(u2) sess.flush() - + # merge User on u2's pk with # no "data". # value isn't whacked from the destination # dict. u3 = sess.merge(User(id=2)) eq_(u3.__dict__['data'], "foo") - + # make a change. u3.data = 'bar' - + # merge another no-"data" user. # attribute maintains modified state. # (usually autoflush would have happened @@ -281,12 +281,12 @@ class MergeTest(_fixtures.FixtureTest): u5 = User(id=3, data="foo") sess.add(u5) sess.flush() - + # blow it away from u5, but don't # mark as expired. so it would just # be blank. del u5.data - + # the merge adds expiry to the # attribute so that it loads. # not sure if I like this - it currently is needed @@ -300,8 +300,8 @@ class MergeTest(_fixtures.FixtureTest): u6.data = None u7 = sess.merge(User(id=3)) assert u6.__dict__['data'] is None - - + + @testing.resolve_artifact_names def test_merge_irregular_collection(self): mapper(User, users, properties={ @@ -427,27 +427,27 @@ class MergeTest(_fixtures.FixtureTest): a1 = Address(email_address="asdf", user=u1) sess.add(a1) sess.flush() - + a2 = Address(id=a1.id, email_address="bar", user=User(name="hoho")) a2 = sess.merge(a2) sess.flush() - + # no expire of the attribute - + assert a2.__dict__['user'] is u1 - + # merge succeeded eq_( sess.query(Address).all(), [Address(id=a1.id, email_address="bar")] ) - + # didn't touch user eq_( sess.query(User).all(), [User(name="fred")] ) - + @testing.resolve_artifact_names def test_one_to_many_cascade(self): @@ -492,17 +492,17 @@ class MergeTest(_fixtures.FixtureTest): 'user':relationship(User) }) mapper(User, users) - + u1 = User(id=1, name="u1") a1 =Address(id=1, email_address="a1", user=u1) u2 = User(id=2, name="u2") - + sess = create_session() sess.add_all([a1, u2]) sess.flush() - + a1.user = u2 - + sess2 = create_session() a2 = sess2.merge(a1) eq_( @@ -510,9 +510,9 @@ class MergeTest(_fixtures.FixtureTest): ([u2], (), [attributes.PASSIVE_NO_RESULT]) ) assert a2 in sess2.dirty - + sess.refresh(a1) - + sess2 = create_session() a2 = sess2.merge(a1, load=False) eq_( @@ -520,7 +520,7 @@ class MergeTest(_fixtures.FixtureTest): ((), [u1], ()) ) assert a2 not in sess2.dirty - + @testing.resolve_artifact_names def test_many_to_many_cascade(self): @@ -609,18 +609,18 @@ class MergeTest(_fixtures.FixtureTest): sess.add(u) sess.commit() sess.close() - + u2 = User(id=7, name=None, address=None) u3 = sess.merge(u2) assert u3.name is None assert u3.address is None - + sess.close() - + a1 = Address(id=1, user=None) a2 = sess.merge(a1) assert a2.user is None - + @testing.resolve_artifact_names def test_transient_no_load(self): mapper(User, users) @@ -863,7 +863,7 @@ class MergeTest(_fixtures.FixtureTest): 'uid':synonym('id'), 'foobar':comparable_property(User.Comparator,User.value), }) - + sess = create_session() u = User() u.name = 'ed' @@ -875,7 +875,7 @@ class MergeTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_cascade_doesnt_blowaway_manytoone(self): """a merge test that was fixed by [ticket:1202]""" - + s = create_session(autoflush=True) mapper(User, users, properties={ 'addresses':relationship(mapper(Address, addresses),backref='user')}) @@ -889,7 +889,7 @@ class MergeTest(_fixtures.FixtureTest): eq_(after_id, other_id) eq_(before_id, after_id) eq_(a1.user, a2.user) - + @testing.resolve_artifact_names def test_cascades_dont_autoflush(self): sess = create_session(autoflush=True) @@ -930,7 +930,7 @@ class MergeTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_dont_expire_pending(self): """test that pending instances aren't expired during a merge.""" - + mapper(User, users) u = User(id=7) sess = create_session(autoflush=True, autocommit=False) @@ -939,40 +939,40 @@ class MergeTest(_fixtures.FixtureTest): def go(): eq_(u.name, None) self.assert_sql_count(testing.db, go, 0) - + @testing.resolve_artifact_names def test_option_state(self): """test that the merged takes on the MapperOption characteristics of that which is merged. - + """ class Option(MapperOption): propagate_to_loaders = True - + opt1, opt2 = Option(), Option() sess = sessionmaker()() - + umapper = mapper(User, users) - + sess.add_all([ User(id=1, name='u1'), User(id=2, name='u2'), ]) sess.commit() - + sess2 = sessionmaker()() s2_users = sess2.query(User).options(opt2).all() - + # test 1. no options are replaced by merge options sess = sessionmaker()() s1_users = sess.query(User).all() - + for u in s1_users: ustate = attributes.instance_state(u) eq_(ustate.load_path, ()) eq_(ustate.load_options, set()) - + for u in s2_users: sess.merge(u) @@ -980,7 +980,7 @@ class MergeTest(_fixtures.FixtureTest): ustate = attributes.instance_state(u) eq_(ustate.load_path, (umapper, )) eq_(ustate.load_options, set([opt2])) - + # test 2. present options are replaced by merge options sess = sessionmaker()() s1_users = sess.query(User).options(opt1).all() @@ -991,12 +991,12 @@ class MergeTest(_fixtures.FixtureTest): for u in s2_users: sess.merge(u) - + for u in s1_users: ustate = attributes.instance_state(u) eq_(ustate.load_path, (umapper, )) eq_(ustate.load_options, set([opt2])) - + class MutableMergeTest(_base.MappedTest): @classmethod @@ -1005,27 +1005,27 @@ class MutableMergeTest(_base.MappedTest): Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('data', PickleType(comparator=operator.eq)) ) - + @classmethod def setup_classes(cls): class Data(_base.ComparableEntity): pass - + @testing.resolve_artifact_names def test_list(self): mapper(Data, data) sess = sessionmaker()() d = Data(data=["this", "is", "a", "list"]) - + sess.add(d) sess.commit() - + d2 = Data(id=d.id, data=["this", "is", "another", "list"]) d3 = sess.merge(d2) eq_(d3.data, ["this", "is", "another", "list"]) - - - + + + class CompositeNullPksTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -1033,19 +1033,19 @@ class CompositeNullPksTest(_base.MappedTest): Column('pk1', String(10), primary_key=True), Column('pk2', String(10), primary_key=True), ) - + @classmethod def setup_classes(cls): class Data(_base.ComparableEntity): pass - + @testing.resolve_artifact_names def test_merge_allow_partial(self): mapper(Data, data) sess = sessionmaker()() - + d1 = Data(pk1="someval", pk2=None) - + def go(): return sess.merge(d1) self.assert_sql_count(testing.db, go, 1) @@ -1060,5 +1060,5 @@ class CompositeNullPksTest(_base.MappedTest): def go(): return sess.merge(d1) self.assert_sql_count(testing.db, go, 0) - + diff --git a/test/orm/test_naturalpks.py b/test/orm/test_naturalpks.py index f9ce7b3ca..18ebb5bba 100644 --- a/test/orm/test_naturalpks.py +++ b/test/orm/test_naturalpks.py @@ -21,7 +21,7 @@ class NaturalPKTest(_base.MappedTest): fk_args = dict(deferrable=True, initially='deferred') else: fk_args = dict(onupdate='cascade') - + users = Table('users', metadata, Column('username', String(50), primary_key=True), Column('fullname', String(100)), @@ -118,7 +118,7 @@ class NaturalPKTest(_base.MappedTest): sess.flush() sess.expunge_all() assert sess.query(User).get('ed').fullname == 'jack' - + @testing.fails_on('sqlite', 'sqlite doesnt support ON UPDATE CASCADE') @testing.fails_on('oracle', 'oracle doesnt support ON UPDATE CASCADE') @@ -177,7 +177,7 @@ class NaturalPKTest(_base.MappedTest): assert sess.query(Address).get('jack1').username is None u1 = sess.query(User).get('fred') eq_(User(username='fred', fullname='jack'), u1) - + @testing.fails_on('sqlite', 'sqlite doesnt support ON UPDATE CASCADE') @testing.fails_on('oracle', 'oracle doesnt support ON UPDATE CASCADE') @@ -243,7 +243,7 @@ class NaturalPKTest(_base.MappedTest): u1 = User(username='jack', fullname='jack') sess.add(u1) sess.flush() - + a1 = Address(email='jack1') u1.address = a1 sess.add(a1) @@ -265,7 +265,7 @@ class NaturalPKTest(_base.MappedTest): sess.expunge_all() eq_([Address(username='ed')], sess.query(Address).all()) - + @testing.fails_on('sqlite', 'sqlite doesnt support ON UPDATE CASCADE') @testing.fails_on('oracle', 'oracle doesnt support ON UPDATE CASCADE') def test_bidirectional_passive(self): @@ -376,7 +376,7 @@ class NaturalPKTest(_base.MappedTest): eq_(['jack'], [u.username for u in r[0].users]) eq_(Item(itemname='item2'), r[1]) eq_(['ed', 'jack'], sorted([u.username for u in r[1].users])) - + sess.expunge_all() u2 = sess.query(User).get(u2.username) u2.username='wendy' @@ -386,41 +386,41 @@ class NaturalPKTest(_base.MappedTest): class TransientExceptionTesst(_fixtures.FixtureTest): run_inserts = None - + @testing.resolve_artifact_names def test_transient_exception(self): """An object that goes from a pk value to transient/pending doesn't count as a "pk" switch. - + """ mapper(User, users) mapper(Address, addresses, properties={'user':relationship(User)}) - + sess = create_session() u1 = User(id=5, name='u1') ad1 = Address(email_address='e1', user=u1) sess.add_all([u1, ad1]) sess.flush() - + make_transient(u1) u1.id = None u1.username='u2' sess.add(u1) sess.flush() - + eq_(ad1.user_id, 5) - + sess.expire_all() eq_(ad1.user_id, 5) ne_(u1.id, 5) ne_(u1.id, None) eq_(sess.query(User).count(), 2) - + class ReversePKsTest(_base.MappedTest): """reverse the primary keys of two entities and ensure bookkeeping succeeds.""" - - + + @classmethod def define_tables(cls, metadata): Table( @@ -429,7 +429,7 @@ class ReversePKsTest(_base.MappedTest): Column('status', Integer, primary_key=True), Column('username', Unicode(50), nullable=False), ) - + @classmethod def setup_classes(cls): class User(_base.ComparableEntity): @@ -441,11 +441,11 @@ class ReversePKsTest(_base.MappedTest): @testing.resolve_artifact_names def test_reverse(self): PUBLISHED, EDITABLE, ARCHIVED = 1, 2, 3 - + mapper(User, user) session = sa.orm.sessionmaker()() - + a_published = User(1, PUBLISHED, u'a') session.add(a_published) session.commit() @@ -473,7 +473,7 @@ class ReversePKsTest(_base.MappedTest): assert session.query(User).get([1, PUBLISHED]) is a_published assert session.query(User).get([1, EDITABLE]) is a_editable - + class SelfReferentialTest(_base.MappedTest): # mssql, mysql don't allow # ON UPDATE on self-referential keys @@ -485,7 +485,7 @@ class SelfReferentialTest(_base.MappedTest): fk_args = dict(deferrable=True, initially='deferred') else: fk_args = dict(onupdate='cascade') - + Table('nodes', metadata, Column('name', String(50), primary_key=True), Column('parent', String(50), @@ -515,7 +515,7 @@ class SelfReferentialTest(_base.MappedTest): n4 = Node(name='n13', parentnode=n1) sess.add_all([n2, n3, n4]) sess.commit() - + n1.name = 'new n1' sess.commit() eq_(['new n1', 'new n1', 'new n1'], @@ -686,7 +686,7 @@ class NonPKCascadeTest(_base.MappedTest): class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): """A primary key mutation cascades onto a foreign key that is itself a primary key.""" - + @classmethod def define_tables(cls, metadata): if testing.against('oracle'): @@ -714,7 +714,7 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): pass class Address(_base.ComparableEntity): pass - + @testing.fails_on('sqlite', 'sqlite doesnt support ON UPDATE CASCADE') @testing.fails_on('oracle', 'oracle doesnt support ON UPDATE CASCADE') def test_onetomany_passive(self): @@ -724,20 +724,20 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): @testing.fails_on_everything_except('sqlite', 'oracle', '+zxjdbc') def test_onetomany_nonpassive(self): self._test_onetomany(False) - + def test_o2m_change_passive(self): self._test_o2m_change(True) - + def test_o2m_change_nonpassive(self): self._test_o2m_change(False) @testing.resolve_artifact_names def _test_o2m_change(self, passive_updates): """Change the PK of a related entity to another. - + "on update cascade" is not involved here, so the mapper has to do the UPDATE itself. - + """ mapper(User, users, properties={ 'addresses':relationship(Address, @@ -748,10 +748,10 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): a1 = Address(username='ed', email='ed@host1') u1 = User(username='ed', addresses=[a1]) u2 = User(username='jack') - + sess.add_all([a1, u1, u2]) sess.flush() - + a1.username = 'jack' sess.flush() @@ -783,17 +783,17 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): u1.addresses.remove(a1) u2.addresses.append(a1) sess.flush() - + @testing.fails_on('oracle', 'oracle doesnt support ON UPDATE CASCADE ' 'but requires referential integrity') @testing.fails_on('sqlite', 'sqlite doesnt support ON UPDATE CASCADE') def test_change_m2o_passive(self): self._test_change_m2o(True) - + @testing.fails_on_everything_except('sqlite', 'oracle', '+zxjdbc') def test_change_m2o_nonpassive(self): self._test_change_m2o(False) - + @testing.resolve_artifact_names def _test_change_m2o(self, passive_updates): mapper(User, users) @@ -806,11 +806,11 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): a1 = Address(user=u1, email='foo@bar') sess.add_all([u1, a1]) sess.flush() - + u1.username='edmodified' sess.flush() eq_(a1.username, 'edmodified') - + sess.expire_all() eq_(a1.username, 'edmodified') @@ -834,11 +834,11 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): a1 = Address(user=u1, email='foo@bar') sess.add_all([u1, u2, a1]) sess.flush() - + a1.user = u2 sess.flush() - - + + @testing.resolve_artifact_names def test_rowswitch_doesntfire(self): mapper(User, users) @@ -849,11 +849,11 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): sess = create_session() u1 = User(username='ed') a1 = Address(user=u1, email='ed@host1') - + sess.add(u1) sess.add(a1) sess.flush() - + sess.delete(u1) sess.delete(a1) @@ -863,7 +863,7 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): sess.add(a2) from test.lib.assertsql import CompiledSQL - + # test that the primary key columns of addresses are not # being updated as well, since this is a row switch. self.assert_sql_execution(testing.db, @@ -875,22 +875,22 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): {'etc': 'foo', 'addresses_username':'ed', 'addresses_email':'ed@host1'} ), ) - - + + @testing.resolve_artifact_names def _test_onetomany(self, passive_updates): """Change the PK of a related entity via foreign key cascade. - + For databases that require "on update cascade", the mapper has to identify the row by the new value, not the old, when it does the update. - + """ mapper(User, users, properties={ 'addresses':relationship(Address, passive_updates=passive_updates)}) mapper(Address, addresses) - + sess = create_session() a1, a2 = Address(username='ed', email='ed@host1'),\ Address(username='ed', email='ed@host2') @@ -901,7 +901,7 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): eq_(a2.username, 'ed') eq_(sa.select([addresses.c.username]).execute().fetchall(), [('ed',), ('ed',)]) - + u1.username = 'jack' a2.email='ed@host3' sess.flush() @@ -914,7 +914,7 @@ class CascadeToFKPKTest(_base.MappedTest, testing.AssertsCompiledSQL): class JoinedInheritanceTest(_base.MappedTest): """Test cascades of pk->pk/fk on joined table inh.""" - + # mssql doesn't allow ON UPDATE on self-referential keys __unsupported_on__ = ('mssql',) @@ -929,7 +929,7 @@ class JoinedInheritanceTest(_base.MappedTest): Column('name', String(50), primary_key=True), Column('type', String(50), nullable=False), test_needs_fk=True) - + Table('engineer', metadata, Column('name', String(50), ForeignKey('person.name', **fk_args), primary_key=True), @@ -965,12 +965,12 @@ class JoinedInheritanceTest(_base.MappedTest): @testing.fails_on_everything_except('sqlite', 'oracle', '+zxjdbc') def test_pk_nonpassive(self): self._test_pk(False) - + @testing.fails_on('sqlite', 'sqlite doesnt support ON UPDATE CASCADE') @testing.fails_on('oracle', 'oracle doesnt support ON UPDATE CASCADE') def test_fk_passive(self): self._test_fk(True) - + # PG etc. need passive=True to allow PK->PK cascade @testing.fails_on_everything_except('sqlite', 'mysql+zxjdbc', 'oracle', 'postgresql+zxjdbc') @@ -1000,7 +1000,7 @@ class JoinedInheritanceTest(_base.MappedTest): e1.name = 'wally' e1.primary_language = 'c++' sess.commit() - + @testing.resolve_artifact_names def _test_fk(self, passive_updates): mapper(Person, person, polymorphic_on=person.c.type, @@ -1015,9 +1015,9 @@ class JoinedInheritanceTest(_base.MappedTest): }) mapper(Manager, manager, inherits=Person, polymorphic_identity='manager') - + sess = sa.orm.sessionmaker()() - + m1 = Manager(name='dogbert', paperwork='lots') e1, e2 = \ Engineer(name='dilbert', primary_language='java', boss=m1),\ @@ -1030,14 +1030,14 @@ class JoinedInheritanceTest(_base.MappedTest): eq_(e1.boss_name, 'dogbert') eq_(e2.boss_name, 'dogbert') sess.expire_all() - + m1.name = 'pointy haired' e1.primary_language = 'scala' e2.primary_language = 'cobol' sess.commit() - + eq_(e1.boss_name, 'pointy haired') eq_(e2.boss_name, 'pointy haired') - - - + + + diff --git a/test/orm/test_onetoone.py b/test/orm/test_onetoone.py index 7097a266e..ff0ac508a 100644 --- a/test/orm/test_onetoone.py +++ b/test/orm/test_onetoone.py @@ -47,7 +47,7 @@ class O2OTest(_base.MappedTest): session.add(j) p = Port(name='fa0/1') session.add(p) - + j.port=p session.flush() jid = j.id diff --git a/test/orm/test_pickled.py b/test/orm/test_pickled.py index 972b298af..3383c48b9 100644 --- a/test/orm/test_pickled.py +++ b/test/orm/test_pickled.py @@ -18,7 +18,7 @@ User, EmailUser = None, None class PickleTest(_fixtures.FixtureTest): run_inserts = None - + @testing.resolve_artifact_names def test_transient(self): mapper(User, users, properties={ @@ -40,7 +40,7 @@ class PickleTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_no_mappers(self): - + umapper = mapper(User, users) u1 = User(name='ed') u1_pickled = pickle.dumps(u1, -1) @@ -67,21 +67,21 @@ class PickleTest(_fixtures.FixtureTest): # this fails unless the InstanceState # compiles the mapper eq_(str(u1), "User(name='ed')") - + @testing.resolve_artifact_names def test_serialize_path(self): umapper = mapper(User, users, properties={ 'addresses':relationship(Address, backref="user") }) amapper = mapper(Address, addresses) - + # this is a "relationship" path with mapper, key, mapper, key p1 = (umapper, 'addresses', amapper, 'email_address') eq_( interfaces.deserialize_path(interfaces.serialize_path(p1)), p1 ) - + # this is a "mapper" path with mapper, key, mapper, no key # at the end. p2 = (umapper, 'addresses', amapper, ) @@ -89,14 +89,14 @@ class PickleTest(_fixtures.FixtureTest): interfaces.deserialize_path(interfaces.serialize_path(p2)), p2 ) - + # test a blank path p3 = () eq_( interfaces.deserialize_path(interfaces.serialize_path(p3)), p3 ) - + @testing.resolve_artifact_names def test_class_deferred_cols(self): mapper(User, users, properties={ @@ -134,7 +134,7 @@ class PickleTest(_fixtures.FixtureTest): 'addresses':relationship(Address, lazy='noload') }) mapper(Address, addresses) - + sess = Session() u1 = User(name='ed', addresses=[ Address( @@ -145,16 +145,16 @@ class PickleTest(_fixtures.FixtureTest): sess.add(u1) sess.commit() sess.close() - + u1 = sess.query(User).options( lazyload(User.addresses) ).first() u2 = pickle.loads(pickle.dumps(u1)) - + sess = Session() sess.add(u2) assert u2.addresses - + @testing.resolve_artifact_names def test_instance_deferred_cols(self): mapper(User, users, properties={ @@ -192,11 +192,11 @@ class PickleTest(_fixtures.FixtureTest): eq_(u2.name, 'ed') assert 'addresses' not in u2.__dict__ ad = u2.addresses[0] - + # mapper options now transmit over merge(), # new as of 0.6, so email_address is deferred. - assert 'email_address' not in ad.__dict__ - + assert 'email_address' not in ad.__dict__ + eq_(ad.email_address, 'ed@bar.com') eq_(u2, User(name='ed', addresses=[Address(email_address='ed@bar.com')])) @@ -218,7 +218,7 @@ class PickleTest(_fixtures.FixtureTest): for protocol in -1, 0, 1, 2: u2 = pickle.loads(pickle.dumps(u1, protocol)) eq_(u1, u2) - + @testing.resolve_artifact_names def test_options_with_descriptors(self): mapper(User, users, properties={ @@ -241,17 +241,17 @@ class PickleTest(_fixtures.FixtureTest): ]: opt2 = pickle.loads(pickle.dumps(opt)) eq_(opt.key, opt2.key) - + u1 = sess.query(User).options(opt).first() - + u2 = pickle.loads(pickle.dumps(u1)) - + def test_collection_setstate(self): """test a particular cycle that requires CollectionAdapter to not rely upon InstanceState to deserialize.""" - + global Child1, Child2, Parent, Screen - + m = MetaData() c1 = Table('c1', m, Column('parent_id', String, @@ -272,7 +272,7 @@ class PickleTest(_fixtures.FixtureTest): class Parent(_base.ComparableEntity): pass - + mapper(Parent, p, properties={ 'children1':relationship(Child1), 'children2':relationship(Child2) @@ -289,7 +289,7 @@ class PickleTest(_fixtures.FixtureTest): screen1.errors = [obj.children1, obj.children2] screen2 = Screen(Child2(), screen1) pickle.loads(pickle.dumps(screen2)) - + class PolymorphicDeferredTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -339,7 +339,7 @@ class CustomSetupTeardownTest(_fixtures.FixtureTest): def test_rebuild_state(self): """not much of a 'test', but illustrate how to remove instance-level state before pickling. - + """ mapper(User, users) @@ -349,12 +349,12 @@ class CustomSetupTeardownTest(_fixtures.FixtureTest): u2 = pickle.loads(pickle.dumps(u1)) attributes.manager_of_class(User).setup_instance(u2) assert attributes.instance_state(u2) - + class UnpickleSA05Test(_fixtures.FixtureTest): """test loading picklestrings from SQLA 0.5.""" - + __requires__ = ('python2',) - + @testing.resolve_artifact_names def test_one(self): mapper(User, users, properties={ diff --git a/test/orm/test_query.py b/test/orm/test_query.py index 15ffaff2f..fba77c783 100644 --- a/test/orm/test_query.py +++ b/test/orm/test_query.py @@ -66,7 +66,7 @@ class RowTupleTest(QueryTest): mapper(User, users, properties={ 'uname':users.c.name }) - + row = create_session().\ query(User.id, User.uname).\ filter(User.id==7).first() @@ -125,7 +125,7 @@ class RowTupleTest(QueryTest): q.column_descriptions, asserted ) - + class GetTest(QueryTest): def test_get(self): s = create_session() @@ -140,14 +140,14 @@ class GetTest(QueryTest): def test_get_composite_pk_no_result(self): s = Session() assert s.query(CompositePk).get((100,100)) is None - + def test_get_composite_pk_result(self): s = Session() one_two = s.query(CompositePk).get((1,2)) assert one_two.i == 1 assert one_two.j == 2 assert one_two.k == 3 - + def test_get_too_few_params(self): s = Session() q = s.query(CompositePk) @@ -162,16 +162,16 @@ class GetTest(QueryTest): s = Session() q = s.query(CompositePk) assert_raises(sa_exc.InvalidRequestError, q.get, (7, 10, 100)) - + def test_get_null_pk(self): """test that a mapping which can have None in a PK (i.e. map to an outerjoin) works with get().""" - + s = users.outerjoin(addresses) - + class UserThing(_base.ComparableEntity): pass - + mapper(UserThing, s, properties={ 'id':(users.c.id, addresses.c.user_id), 'address_id':addresses.c.id, @@ -186,11 +186,11 @@ class GetTest(QueryTest): """test that get()/load() does not use preexisting filter/etc. criterion""" s = create_session() - + q = s.query(User).join('addresses').filter(Address.user_id==8) assert_raises(sa_exc.InvalidRequestError, q.get, 7) assert_raises(sa_exc.InvalidRequestError, s.query(User).filter(User.id==7).get, 19) - + # order_by()/get() doesn't raise s.query(User).order_by(User.id).get(8) @@ -244,7 +244,7 @@ class GetTest(QueryTest): # Py2K ustring = 'petit voix m\xe2\x80\x99a'.decode('utf-8') # end Py2K - + table.insert().execute(id=ustring, data=ustring) class LocalFoo(Base): pass @@ -298,7 +298,7 @@ class GetTest(QueryTest): class InvalidGenerationsTest(QueryTest, AssertsCompiledSQL): def test_no_limit_offset(self): s = create_session() - + for q in ( s.query(User).limit(2), s.query(User).offset(2), @@ -315,31 +315,31 @@ class InvalidGenerationsTest(QueryTest, AssertsCompiledSQL): assert_raises(sa_exc.InvalidRequestError, q.group_by, 'foo') assert_raises(sa_exc.InvalidRequestError, q.having, 'foo') - + q.enable_assertions(False).join("addresses") q.enable_assertions(False).filter(User.name=='ed') q.enable_assertions(False).order_by('foo') q.enable_assertions(False).group_by('foo') - + def test_no_from(self): s = create_session() - + q = s.query(User).select_from(users) assert_raises(sa_exc.InvalidRequestError, q.select_from, users) q = s.query(User).join('addresses') assert_raises(sa_exc.InvalidRequestError, q.select_from, users) - + q = s.query(User).order_by(User.id) assert_raises(sa_exc.InvalidRequestError, q.select_from, users) assert_raises(sa_exc.InvalidRequestError, q.select_from, users) - + q.enable_assertions(False).select_from(users) - + # this is fine, however q.from_self() - + def test_invalid_select_from(self): s = create_session() q = s.query(User) @@ -351,15 +351,15 @@ class InvalidGenerationsTest(QueryTest, AssertsCompiledSQL): q = s.query(User) assert_raises(sa_exc.ArgumentError, q.from_statement, User.id==5) assert_raises(sa_exc.ArgumentError, q.from_statement, users.join(addresses)) - + def test_invalid_column(self): s = create_session() q = s.query(User) assert_raises(sa_exc.InvalidRequestError, q.add_column, object()) - + def test_distinct(self): """test that a distinct() call is not valid before 'clauseelement' conditions.""" - + s = create_session() q = s.query(User).distinct() assert_raises(sa_exc.InvalidRequestError, q.select_from, User) @@ -374,7 +374,7 @@ class InvalidGenerationsTest(QueryTest, AssertsCompiledSQL): assert_raises(sa_exc.InvalidRequestError, q.select_from, User) assert_raises(sa_exc.InvalidRequestError, q.from_statement, text("select * from table")) assert_raises(sa_exc.InvalidRequestError, q.with_polymorphic, User) - + def test_cancel_order_by(self): s = create_session() @@ -399,16 +399,16 @@ class InvalidGenerationsTest(QueryTest, AssertsCompiledSQL): # after False was set, this should pass q._no_select_modifiers("foo") - + def test_mapper_zero(self): s = create_session() - + q = s.query(User, Address) assert_raises(sa_exc.InvalidRequestError, q.get, 5) - + def test_from_statement(self): s = create_session() - + q = s.query(User).filter(User.id==5) assert_raises(sa_exc.InvalidRequestError, q.from_statement, "x") @@ -423,7 +423,7 @@ class InvalidGenerationsTest(QueryTest, AssertsCompiledSQL): q = s.query(User).order_by(User.name) assert_raises(sa_exc.InvalidRequestError, q.from_statement, "x") - + class OperatorTest(QueryTest, AssertsCompiledSQL): """test sql.Comparator implementation for MapperProperties""" @@ -455,7 +455,7 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): def test_comparison(self): create_session().query(User) ualias = aliased(User) - + for (py_op, fwd_op, rev_op) in ((operator.lt, '<', '>'), (operator.gt, '>', '<'), (operator.eq, '=', '='), @@ -486,7 +486,7 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): self.assert_(compiled == fwd_sql or compiled == rev_sql, "\n'" + compiled + "'\n does not match\n'" + fwd_sql + "'\n or\n'" + rev_sql + "'") - + def test_negated_null(self): self._test(User.id == None, "users.id IS NULL") self._test(~(User.id==None), "users.id IS NOT NULL") @@ -496,7 +496,7 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): self._test(~(Address.user==None), "addresses.user_id IS NOT NULL") self._test(None == Address.user, "addresses.user_id IS NULL") self._test(~(None == Address.user), "addresses.user_id IS NOT NULL") - + def test_relationship(self): self._test(User.addresses.any(Address.id==17), "EXISTS (SELECT 1 " @@ -506,7 +506,7 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): u7 = User(id=7) attributes.instance_state(u7).commit_all(attributes.instance_dict(u7)) - + self._test(Address.user == u7, ":param_1 = addresses.user_id") self._test(Address.user != u7, "addresses.user_id != :user_id_1 OR addresses.user_id IS NULL") @@ -530,7 +530,7 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): Node.children==None, "NOT (EXISTS (SELECT 1 FROM nodes AS nodes_1 WHERE nodes.id = nodes_1.parent_id))" ) - + self._test( Node.parent==None, "nodes.parent_id IS NULL" @@ -545,12 +545,12 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): nalias.children==None, "NOT (EXISTS (SELECT 1 FROM nodes WHERE nodes_1.id = nodes.parent_id))" ) - + self._test( nalias.children.any(Node.data=='some data'), "EXISTS (SELECT 1 FROM nodes WHERE " "nodes_1.id = nodes.parent_id AND nodes.data = :data_1)") - + # fails, but I think I want this to fail #self._test( # Node.children.any(nalias.data=='some data'), @@ -567,7 +567,7 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): Node.parent.has(Node.data=='some data'), "EXISTS (SELECT 1 FROM nodes AS nodes_1 WHERE nodes_1.id = nodes.parent_id AND nodes_1.data = :data_1)" ) - + self._test( Node.parent == Node(id=7), ":param_1 = nodes.parent_id" @@ -582,11 +582,11 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): nalias.parent != Node(id=7), 'nodes_1.parent_id != :parent_id_1 OR nodes_1.parent_id IS NULL' ) - + self._test( nalias.children.contains(Node(id=7)), "nodes_1.id = :param_1" ) - + def test_op(self): self._test(User.name.op('ilike')('17'), "users.name ilike :name_1") @@ -596,11 +596,11 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): def test_in_on_relationship_not_supported(self): assert_raises(NotImplementedError, Address.user.in_, [User(id=5)]) - + def test_neg(self): self._test(-User.id, "-users.id") self._test(User.id + -User.id, "users.id + -users.id") - + def test_between(self): self._test(User.id.between('a', 'b'), "users.id BETWEEN :id_1 AND :id_2") @@ -623,7 +623,7 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): class ExpressionTest(QueryTest, AssertsCompiledSQL): - + def test_deferred_instances(self): session = create_session() s = session.query(User).filter(and_(addresses.c.email_address == bindparam('emailad'), Address.user_id==User.id)).statement @@ -633,13 +633,13 @@ class ExpressionTest(QueryTest, AssertsCompiledSQL): def test_scalar_subquery(self): session = create_session() - + q = session.query(User.id).filter(User.id==7).subquery() - + q = session.query(User).filter(User.id==q) - + eq_(User(id=7), q.one()) - + def test_label(self): session = create_session() @@ -649,29 +649,29 @@ class ExpressionTest(QueryTest, AssertsCompiledSQL): "SELECT (SELECT users.id FROM users WHERE users.id = :id_1) AS foo", use_default_dialect=True ) - + def test_as_scalar(self): session = create_session() q = session.query(User.id).filter(User.id==7).as_scalar() - + self.assert_compile(session.query(User).filter(User.id.in_(q)), 'SELECT users.id AS users_id, users.name ' 'AS users_name FROM users WHERE users.id ' 'IN (SELECT users.id FROM users WHERE ' 'users.id = :id_1)', use_default_dialect=True) - - + + def test_param_transfer(self): session = create_session() - + q = session.query(User.id).filter(User.id==bindparam('foo')).params(foo=7).subquery() - + q = session.query(User).filter(User.id==q) - + eq_(User(id=7), q.one()) - + def test_in(self): session = create_session() s = session.query(User.id).join(User.addresses).group_by(User.id).having(func.count(Address.id) > 2) @@ -682,17 +682,17 @@ class ExpressionTest(QueryTest, AssertsCompiledSQL): def test_union(self): s = create_session() - + q1 = s.query(User).filter(User.name=='ed').with_labels() q2 = s.query(User).filter(User.name=='fred').with_labels() eq_( s.query(User).from_statement(union(q1, q2).order_by('users_name')).all(), [User(name='ed'), User(name='fred')] ) - + def test_select(self): s = create_session() - + # this is actually not legal on most DBs since the subquery has no alias q1 = s.query(User).filter(User.name=='ed') @@ -703,7 +703,7 @@ class ExpressionTest(QueryTest, AssertsCompiledSQL): "users.name AS users_name FROM users WHERE users.name = :name_1)", dialect=default.DefaultDialect() ) - + def test_join(self): s = create_session() @@ -715,7 +715,7 @@ class ExpressionTest(QueryTest, AssertsCompiledSQL): s.query(User, adalias).join(adalias, User.id==adalias.user_id).all(), [(User(id=7,name=u'jack'), Address(email_address=u'jack@bean.com',user_id=7,id=1))] ) - + # more slice tests are available in test/orm/generative.py class SliceTest(QueryTest): def test_first(self): @@ -726,15 +726,15 @@ class SliceTest(QueryTest): @testing.only_on('sqlite', 'testing execution but db-specific syntax') def test_limit_offset_applies(self): """Test that the expected LIMIT/OFFSET is applied for slices. - + The LIMIT/OFFSET syntax differs slightly on all databases, and query[x:y] executes immediately, so we are asserting against SQL strings using sqlite's syntax. - + """ sess = create_session() q = sess.query(User) - + self.assert_sql(testing.db, lambda: q[10:20], [ ("SELECT users.id AS users_id, users.name AS users_name FROM users LIMIT :param_1 OFFSET :param_2", {'param_1':10, 'param_2':10}) ]) @@ -764,7 +764,7 @@ class SliceTest(QueryTest): ]) - + class FilterTest(QueryTest): def test_basic(self): assert [User(id=7), User(id=8), User(id=9),User(id=10)] == create_session().query(User).all() @@ -776,20 +776,20 @@ class FilterTest(QueryTest): assert [User(id=8), User(id=9)] == list(create_session().query(User).order_by(User.id)[1:3]) assert User(id=8) == create_session().query(User).order_by(User.id)[1] - + assert [] == create_session().query(User).order_by(User.id)[3:3] assert [] == create_session().query(User).order_by(User.id)[0:0] - + @testing.requires.boolean_col_expressions def test_exists(self): sess = create_session(testing.db) - + assert sess.query(exists().where(User.id==9)).scalar() assert not sess.query(exists().where(User.id==29)).scalar() - + def test_one_filter(self): assert [User(id=8), User(id=9)] == create_session().query(User).filter(User.name.endswith('ed')).all() - + def test_contains(self): """test comparing a collection to an object instance.""" @@ -824,15 +824,15 @@ class FilterTest(QueryTest): filter(User.addresses.any(id=4)).all() assert [User(id=9)] == sess.query(User).filter(User.addresses.any(email_address='fred@fred.com')).all() - + # test that any() doesn't overcorrelate assert [User(id=7), User(id=8)] == sess.query(User).join("addresses").filter(~User.addresses.any(Address.email_address=='fred@fred.com')).all() - + # test that the contents are not adapted by the aliased join assert [User(id=7), User(id=8)] == sess.query(User).join("addresses", aliased=True).filter(~User.addresses.any(Address.email_address=='fred@fred.com')).all() assert [User(id=10)] == sess.query(User).outerjoin("addresses", aliased=True).filter(~User.addresses.any()).all() - + @testing.crashes('maxdb', 'can dump core') def test_has(self): sess = create_session() @@ -851,10 +851,10 @@ class FilterTest(QueryTest): # test has() doesnt' get subquery contents adapted by aliased join assert [Address(id=2), Address(id=3), Address(id=4)] == \ sess.query(Address).join("user", aliased=True).filter(Address.user.has(User.name.like('%ed%'), id=8)).order_by(Address.id).all() - + dingaling = sess.query(Dingaling).get(2) assert [User(id=9)] == sess.query(User).filter(User.addresses.any(Address.dingaling==dingaling)).all() - + def test_contains_m2m(self): sess = create_session() item = sess.query(Item).get(3) @@ -864,7 +864,7 @@ class FilterTest(QueryTest): item2 = sess.query(Item).get(5) assert [Order(id=3)] == sess.query(Order).filter(Order.items.contains(item)).filter(Order.items.contains(item2)).all() - + def test_comparison(self): """test scalar comparison to an object instance""" @@ -888,7 +888,7 @@ class FilterTest(QueryTest): # m2m eq_(sess.query(Item).filter(Item.keywords==None).order_by(Item.id).all(), [Item(id=4), Item(id=5)]) eq_(sess.query(Item).filter(Item.keywords!=None).order_by(Item.id).all(), [Item(id=1),Item(id=2), Item(id=3)]) - + def test_filter_by(self): sess = create_session() user = sess.query(User).get(8) @@ -901,10 +901,10 @@ class FilterTest(QueryTest): # one to many generates WHERE NOT EXISTS assert [User(name='chuck')] == sess.query(User).filter_by(addresses = None).all() assert [User(name='chuck')] == sess.query(User).filter_by(addresses = null()).all() - + def test_none_comparison(self): sess = create_session() - + # scalar eq_( [Order(description="order 5")], @@ -914,7 +914,7 @@ class FilterTest(QueryTest): [Order(description="order 5")], sess.query(Order).filter(Order.address_id==null()).all() ) - + # o2o eq_([Address(id=1), Address(id=3), Address(id=4)], sess.query(Address).filter(Address.dingaling==None).order_by(Address.id).all()) @@ -922,11 +922,11 @@ class FilterTest(QueryTest): sess.query(Address).filter(Address.dingaling==null()).order_by(Address.id).all()) eq_([Address(id=2), Address(id=5)], sess.query(Address).filter(Address.dingaling != None).order_by(Address.id).all()) eq_([Address(id=2), Address(id=5)], sess.query(Address).filter(Address.dingaling != null()).order_by(Address.id).all()) - + # m2o eq_([Order(id=5)], sess.query(Order).filter(Order.address==None).all()) eq_([Order(id=1), Order(id=2), Order(id=3), Order(id=4)], sess.query(Order).order_by(Order.id).filter(Order.address!=None).all()) - + # o2m eq_([User(id=10)], sess.query(User).filter(User.addresses==None).all()) eq_([User(id=7),User(id=8),User(id=9)], sess.query(User).filter(User.addresses!=None).order_by(User.id).all()) @@ -942,16 +942,16 @@ class FilterTest(QueryTest): ) - + class SetOpsTest(QueryTest, AssertsCompiledSQL): - + def test_union(self): s = create_session() - + fred = s.query(User).filter(User.name=='fred') ed = s.query(User).filter(User.name=='ed') jack = s.query(User).filter(User.name=='jack') - + eq_(fred.union(ed).order_by(User.name).all(), [User(name='ed'), User(name='fred')] ) @@ -959,17 +959,17 @@ class SetOpsTest(QueryTest, AssertsCompiledSQL): eq_(fred.union(ed, jack).order_by(User.name).all(), [User(name='ed'), User(name='fred'), User(name='jack')] ) - + def test_statement_labels(self): """test that label conflicts don't occur with joins etc.""" - + s = create_session() q1 = s.query(User, Address).join(User.addresses).\ filter(Address.email_address=="ed@wood.com") q2 = s.query(User, Address).join(User.addresses).\ filter(Address.email_address=="jack@bean.com") q3 = q1.union(q2).order_by(User.name) - + eq_( q3.all(), [ @@ -977,11 +977,11 @@ class SetOpsTest(QueryTest, AssertsCompiledSQL): (User(name='jack'), Address(email_address="jack@bean.com")), ] ) - + def test_union_literal_expressions_compile(self): """test that column expressions translate during the _from_statement() portion of union(), others""" - + s = Session() q1 = s.query(User, literal("x")) q2 = s.query(User, literal_column("'y'")) @@ -1011,7 +1011,7 @@ class SetOpsTest(QueryTest, AssertsCompiledSQL): [x['name'] for x in q6.column_descriptions], ['User', 'foo'] ) - + for q in (q3.order_by(User.id, "anon_1_anon_2"), q6.order_by(User.id, "foo")): eq_(q.all(), [ @@ -1025,15 +1025,15 @@ class SetOpsTest(QueryTest, AssertsCompiledSQL): (User(id=10, name=u'chuck'), u'y') ] ) - + def test_union_labeled_anonymous_columns(self): s = Session() - + c1, c2 = column('c1'), column('c2') q1 = s.query(User, c1.label('foo'), c1.label('bar')) q2 = s.query(User, c1.label('foo'), c2.label('bar')) q3 = q1.union(q2) - + eq_( [x['name'] for x in q3.column_descriptions], ['User', 'foo', 'bar'] @@ -1050,12 +1050,12 @@ class SetOpsTest(QueryTest, AssertsCompiledSQL): "FROM users) AS anon_1", use_default_dialect=True ) - + def test_union_mapped_colnames_preserved_across_subquery(self): s = Session() q1 = s.query(User.name) q2 = s.query(User.name) - + # the label names in the subquery are the typical anonymized ones self.assert_compile( q1.union(q2), @@ -1064,15 +1064,15 @@ class SetOpsTest(QueryTest, AssertsCompiledSQL): "UNION SELECT users.name AS users_name FROM users) AS anon_1", use_default_dialect=True ) - + # but in the returned named tuples, # due to [ticket:1942], this should be 'name', not 'users_name' eq_( [x['name'] for x in q1.union(q2).column_descriptions], ['name'] ) - - + + @testing.fails_on('mysql', "mysql doesn't support intersect") def test_intersect(self): s = create_session() @@ -1087,7 +1087,7 @@ class SetOpsTest(QueryTest, AssertsCompiledSQL): eq_(fred.union(ed).intersect(ed.union(jack)).all(), [User(name='ed')] ) - + def test_eager_load(self): s = create_session() @@ -1104,8 +1104,8 @@ class SetOpsTest(QueryTest, AssertsCompiledSQL): ] ) self.assert_sql_count(testing.db, go, 1) - - + + class AggregateTest(QueryTest): def test_sum(self): @@ -1127,7 +1127,7 @@ class AggregateTest(QueryTest): class CountTest(QueryTest): def test_basic(self): s = create_session() - + eq_(s.query(User).count(), 4) eq_(s.query(User).filter(users.c.name.endswith('ed')).count(), 2) @@ -1136,10 +1136,10 @@ class CountTest(QueryTest): s = create_session() q = s.query(User, Address) eq_(q.count(), 20) # cartesian product - + q = s.query(User, Address).join(User.addresses) eq_(q.count(), 5) - + def test_nested(self): s = create_session() q = s.query(User, Address).limit(2) @@ -1150,12 +1150,12 @@ class CountTest(QueryTest): q = s.query(User, Address).join(User.addresses).limit(100) eq_(q.count(), 5) - + def test_cols(self): """test that column-based queries always nest.""" - + s = create_session() - + q = s.query(func.count(distinct(User.name))) eq_(q.count(), 1) @@ -1171,8 +1171,8 @@ class CountTest(QueryTest): q = s.query(Address.user_id) eq_(q.count(), 5) eq_(q.distinct().count(), 3) - - + + class DistinctTest(QueryTest): def test_basic(self): eq_( @@ -1232,9 +1232,9 @@ class HintsTest(QueryTest, AssertsCompiledSQL): def test_hints(self): from sqlalchemy.dialects import mysql dialect = mysql.dialect() - + sess = create_session() - + self.assert_compile( sess.query(User).with_hint(User, 'USE INDEX (col1_index,col2_index)'), "SELECT users.id AS users_id, users.name AS users_name " @@ -1248,7 +1248,7 @@ class HintsTest(QueryTest, AssertsCompiledSQL): "FROM users", dialect=dialect ) - + ualias = aliased(User) self.assert_compile( sess.query(User, ualias).with_hint(ualias, 'USE INDEX (col1_index,col2_index)'). @@ -1259,7 +1259,7 @@ class HintsTest(QueryTest, AssertsCompiledSQL): "ON users.id < users_1.id", dialect=dialect ) - + class TextTest(QueryTest): def test_fulltext(self): @@ -1304,7 +1304,7 @@ class ParentTest(QueryTest): o = sess.query(Order).filter(with_parent(u1, User.orders)).all() assert [Order(description="order 1"), Order(description="order 3"), Order(description="order 5")] == o - + # test generative criterion o = sess.query(Order).with_parent(u1).filter(orders.c.id>2).all() assert [Order(description="order 3"), Order(description="order 5")] == o @@ -1335,7 +1335,7 @@ class ParentTest(QueryTest): def test_with_transient(self): sess = Session() - + q = sess.query(User) u1 = q.filter_by(name='jack').one() utrans = User(id=u1.id) @@ -1350,7 +1350,7 @@ class ParentTest(QueryTest): [Order(description="order 1"), Order(description="order 3"), Order(description="order 5")], o.all() ) - + def test_with_pending_autoflush(self): sess = Session() @@ -1376,9 +1376,9 @@ class ParentTest(QueryTest): sess.query(User).with_parent(opending, 'user').one(), User(id=o1.user_id) ) - - + + class SynonymTest(QueryTest): @@ -1499,7 +1499,7 @@ class ImmediateTest(_fixtures.FixtureTest): filter(User.id.in_([8, 9])). order_by(User.id). one) - + @testing.future def test_getslice(self): @@ -1514,10 +1514,10 @@ class ImmediateTest(_fixtures.FixtureTest): eq_(sess.query(User.id).filter_by(id=0).scalar(), None) eq_(sess.query(User).filter_by(id=7).scalar(), sess.query(User).filter_by(id=7).one()) - + assert_raises(sa.orm.exc.MultipleResultsFound, sess.query(User).scalar) assert_raises(sa.orm.exc.MultipleResultsFound, sess.query(User.id, User.name).scalar) - + @testing.resolve_artifact_names def test_value(self): sess = create_session() @@ -1580,7 +1580,7 @@ class UpdateDeleteTest(_base.MappedTest): @testing.resolve_artifact_names def test_illegal_operations(self): s = create_session() - + for q, mname in ( (s.query(User).limit(2), "limit"), (s.query(User).offset(2), "offset"), @@ -1591,17 +1591,17 @@ class UpdateDeleteTest(_base.MappedTest): ): assert_raises_message(sa_exc.InvalidRequestError, r"Can't call Query.update\(\) when %s\(\) has been called" % mname, q.update, {'name':'ed'}) assert_raises_message(sa_exc.InvalidRequestError, r"Can't call Query.delete\(\) when %s\(\) has been called" % mname, q.delete) - - + + @testing.resolve_artifact_names def test_delete(self): sess = create_session(bind=testing.db, autocommit=False) - + john,jack,jill,jane = sess.query(User).order_by(User.id).all() sess.query(User).filter(or_(User.name == 'john', User.name == 'jill')).delete() - + assert john not in sess and jill not in sess - + eq_(sess.query(User).order_by(User.id).all(), [jack,jane]) @testing.resolve_artifact_names @@ -1631,53 +1631,53 @@ class UpdateDeleteTest(_base.MappedTest): assert john not in sess and jill not in sess sess.rollback() assert john in sess and jill in sess - + @testing.resolve_artifact_names def test_delete_without_session_sync(self): sess = create_session(bind=testing.db, autocommit=False) - + john,jack,jill,jane = sess.query(User).order_by(User.id).all() sess.query(User).filter(or_(User.name == 'john', User.name == 'jill')).delete(synchronize_session=False) - + assert john in sess and jill in sess - + eq_(sess.query(User).order_by(User.id).all(), [jack,jane]) @testing.resolve_artifact_names def test_delete_with_fetch_strategy(self): sess = create_session(bind=testing.db, autocommit=False) - + john,jack,jill,jane = sess.query(User).order_by(User.id).all() sess.query(User).filter(or_(User.name == 'john', User.name == 'jill')).delete(synchronize_session='fetch') - + assert john not in sess and jill not in sess - + eq_(sess.query(User).order_by(User.id).all(), [jack,jane]) @testing.fails_on('mysql', 'FIXME: unknown') @testing.resolve_artifact_names def test_delete_invalid_evaluation(self): sess = create_session(bind=testing.db, autocommit=False) - + john,jack,jill,jane = sess.query(User).order_by(User.id).all() - + assert_raises(sa_exc.InvalidRequestError, sess.query(User).filter(User.name == select([func.max(User.name)])).delete, synchronize_session='evaluate' ) - + sess.query(User).filter(User.name == select([func.max(User.name)])).delete(synchronize_session='fetch') - + assert john not in sess - + eq_(sess.query(User).order_by(User.id).all(), [jack,jill,jane]) @testing.resolve_artifact_names def test_update(self): sess = create_session(bind=testing.db, autocommit=False) - + john,jack,jill,jane = sess.query(User).order_by(User.id).all() sess.query(User).filter(User.age > 29).update({'age': User.age - 10}, synchronize_session='evaluate') - + eq_([john.age, jack.age, jill.age, jane.age], [25,37,29,27]) eq_(sess.query(User.age).order_by(User.id).all(), zip([25,37,29,27])) @@ -1702,7 +1702,7 @@ class UpdateDeleteTest(_base.MappedTest): ) class Data(_base.ComparableEntity): pass - + mapper(Data, data, properties={'cnt':data.c.counter}) metadata.create_all() d1 = Data() @@ -1713,12 +1713,12 @@ class UpdateDeleteTest(_base.MappedTest): sess.query(Data).update({Data.cnt:Data.cnt + 1}) sess.flush() - + eq_(d1.cnt, 1) sess.query(Data).update({Data.cnt:Data.cnt + 1}, 'fetch') sess.flush() - + eq_(d1.cnt, 2) sess.close() @@ -1738,19 +1738,19 @@ class UpdateDeleteTest(_base.MappedTest): sess = create_session(bind=testing.db, autocommit=False, autoflush=False) john,jack,jill,jane = sess.query(User).order_by(User.id).all() - + john.age = 50 jack.age = 37 - + # autoflush is false. therefore our '50' and '37' are getting blown away by this operation. - + sess.query(User).filter(User.age > 29).update({'age': User.age - 10}, synchronize_session='evaluate') for x in (john, jack, jill, jane): assert not sess.is_modified(x) eq_([john.age, jack.age, jill.age, jane.age], [25,37,29,27]) - + john.age = 25 assert john in sess.dirty assert jack in sess.dirty @@ -1780,16 +1780,16 @@ class UpdateDeleteTest(_base.MappedTest): assert jill not in sess.dirty assert sess.is_modified(john) assert not sess.is_modified(jack) - - + + @testing.resolve_artifact_names def test_update_with_expire_strategy(self): sess = create_session(bind=testing.db, autocommit=False) - + john,jack,jill,jane = sess.query(User).order_by(User.id).all() sess.query(User).filter(User.age > 29).update({'age': User.age - 10}, synchronize_session='fetch') - + eq_([john.age, jack.age, jill.age, jane.age], [25,37,29,27]) eq_(sess.query(User.age).order_by(User.id).all(), zip([25,37,29,27])) @@ -1847,23 +1847,23 @@ class UpdateDeleteTest(_base.MappedTest): @testing.resolve_artifact_names def test_update_all(self): sess = create_session(bind=testing.db, autocommit=False) - + john,jack,jill,jane = sess.query(User).order_by(User.id).all() sess.query(User).update({'age': 42}, synchronize_session='evaluate') - + eq_([john.age, jack.age, jill.age, jane.age], [42,42,42,42]) eq_(sess.query(User.age).order_by(User.id).all(), zip([42,42,42,42])) @testing.resolve_artifact_names def test_delete_all(self): sess = create_session(bind=testing.db, autocommit=False) - + john,jack,jill,jane = sess.query(User).order_by(User.id).all() sess.query(User).delete(synchronize_session='evaluate') - + assert not (john in sess or jack in sess or jill in sess or jane in sess) eq_(sess.query(User).count(), 0) - + class StatementOptionsTest(QueryTest): @@ -1892,13 +1892,13 @@ class StatementOptionsTest(QueryTest): class OptionsTest(QueryTest): """Test the _get_paths() method of PropertyOption.""" - + def _option_fixture(self, *arg): from sqlalchemy.orm import interfaces class Opt(interfaces.PropertyOption): pass return Opt(arg) - + def _make_path(self, path): r = [] for i, item in enumerate(path): @@ -1907,39 +1907,39 @@ class OptionsTest(QueryTest): item = class_mapper(item) r.append(item) return tuple(r) - + def _assert_path_result(self, opt, q, paths, mappers): eq_( opt._get_paths(q, False), ([self._make_path(p) for p in paths], [class_mapper(c) for c in mappers]) ) - + def test_get_path_one_level_string(self): sess = Session() q = sess.query(User) - + opt = self._option_fixture("addresses") self._assert_path_result(opt, q, [(User, 'addresses')], [User]) def test_get_path_one_level_attribute(self): sess = Session() q = sess.query(User) - + opt = self._option_fixture(User.addresses) self._assert_path_result(opt, q, [(User, 'addresses')], [User]) def test_get_path_one_level_with_unrelated(self): sess = Session() q = sess.query(Order) - + opt = self._option_fixture("addresses") self._assert_path_result(opt, q, [], []) def test_path_multilevel_string(self): sess = Session() q = sess.query(User) - + opt = self._option_fixture("orders.items.keywords") self._assert_path_result(opt, q, [ (User, 'orders'), @@ -1951,7 +1951,7 @@ class OptionsTest(QueryTest): def test_path_multilevel_attribute(self): sess = Session() q = sess.query(User) - + opt = self._option_fixture(User.orders, Order.items, Item.keywords) self._assert_path_result(opt, q, [ (User, 'orders'), @@ -2013,10 +2013,10 @@ class OptionsTest(QueryTest): mapper(SubAddr, inherits=Address, properties={ 'flub':relationship(Dingaling) }) - + q = sess.query(Address) opt = self._option_fixture(SubAddr.flub) - + self._assert_path_result(opt, q, [(Address, 'flub')], [SubAddr]) def test_from_subclass_to_subclass_attr(self): @@ -2026,10 +2026,10 @@ class OptionsTest(QueryTest): mapper(SubAddr, inherits=Address, properties={ 'flub':relationship(Dingaling) }) - + q = sess.query(SubAddr) opt = self._option_fixture(SubAddr.flub) - + self._assert_path_result(opt, q, [(SubAddr, 'flub')], [SubAddr]) def test_from_base_to_base_attr_via_subclass(self): @@ -2039,10 +2039,10 @@ class OptionsTest(QueryTest): mapper(SubAddr, inherits=Address, properties={ 'flub':relationship(Dingaling) }) - + q = sess.query(Address) opt = self._option_fixture(SubAddr.user) - + self._assert_path_result(opt, q, [(Address, 'user')], [Address]) def test_of_type(self): @@ -2050,10 +2050,10 @@ class OptionsTest(QueryTest): class SubAddr(Address): pass mapper(SubAddr, inherits=Address) - + q = sess.query(User) opt = self._option_fixture(User.addresses.of_type(SubAddr), SubAddr.user) - + self._assert_path_result(opt, q, [ (User, 'addresses'), (User, 'addresses', SubAddr, 'user') @@ -2066,15 +2066,15 @@ class OptionsTest(QueryTest): mapper(SubAddr, inherits=Address, properties={ 'flub':relationship(Dingaling) }) - + q = sess.query(User) opt = self._option_fixture(User.addresses.of_type(SubAddr), SubAddr.flub) - + self._assert_path_result(opt, q, [ (User, 'addresses'), (User, 'addresses', SubAddr, 'flub') ], [User, SubAddr]) - + def test_aliased_single(self): sess = Session() ualias = aliased(User) @@ -2109,4 +2109,4 @@ class OptionsTest(QueryTest): ) opt = self._option_fixture(Address.user, User.addresses) self._assert_path_result(opt, q, [], []) - + diff --git a/test/orm/test_relationships.py b/test/orm/test_relationships.py index 39480d79f..feb5c8503 100644 --- a/test/orm/test_relationships.py +++ b/test/orm/test_relationships.py @@ -103,22 +103,22 @@ class CompositeSelfRefFKTest(_base.MappedTest): """Tests a composite FK where, in the relationship(), one col points to itself in the same table. - + this is a very unusual case:: - + company employee ---------- ---------- company_id <--- company_id ------+ name ^ | +------------+ - + emp_id <---------+ name | reports_to_id ---+ - + employee joins to its sub-employees both on reports_to_id, *and on company_id to itself*. - + """ @classmethod @@ -151,7 +151,7 @@ class CompositeSelfRefFKTest(_base.MappedTest): self.company = company self.emp_id = emp_id self.reports_to = reports_to - + @testing.resolve_artifact_names def test_explicit(self): mapper(Company, company_t) @@ -198,7 +198,7 @@ class CompositeSelfRefFKTest(_base.MappedTest): }) self._test() - + @testing.resolve_artifact_names def test_very_explicit(self): mapper(Company, company_t) @@ -215,7 +215,7 @@ class CompositeSelfRefFKTest(_base.MappedTest): }) self._test() - + @testing.resolve_artifact_names def _test(self): sess = create_session() @@ -398,7 +398,7 @@ class FKsAsPksTest(_base.MappedTest): test_needs_autoincrement=True), Column("foo",Integer,), test_needs_fk=True) - + Table("tableB",metadata, Column("id",Integer,ForeignKey("tableA.id"),primary_key=True), test_needs_fk=True) @@ -415,16 +415,16 @@ class FKsAsPksTest(_base.MappedTest): def test_onetoone_switch(self): """test that active history is enabled on a one-to-many/one that has use_get==True""" - + mapper(A, tableA, properties={ 'b':relationship(B, cascade="all,delete-orphan", uselist=False)}) mapper(B, tableB) - + configure_mappers() assert A.b.property.strategy.use_get - + sess = create_session() - + a1 = A() sess.add(a1) sess.flush() @@ -432,7 +432,7 @@ class FKsAsPksTest(_base.MappedTest): a1 = sess.query(A).first() a1.b = B() sess.flush() - + @testing.resolve_artifact_names def test_no_delete_PK_AtoB(self): """A cant be deleted without B because B would have no PK value.""" @@ -531,7 +531,7 @@ class FKsAsPksTest(_base.MappedTest): def test_delete_cascade_AtoB(self): """No 'blank the PK' error when the child is to be deleted as part of a cascade""" - + for cascade in ("save-update, delete", #"save-update, delete-orphan", "save-update, delete, delete-orphan"): @@ -597,7 +597,7 @@ class FKsAsPksTest(_base.MappedTest): class UniqueColReferenceSwitchTest(_base.MappedTest): """test a relationship based on a primary join against a unique non-pk column""" - + @classmethod def define_tables(cls, metadata): Table("table_a", metadata, @@ -614,7 +614,7 @@ class UniqueColReferenceSwitchTest(_base.MappedTest): ForeignKey('table_a.ident'), nullable=False), ) - + @classmethod def setup_classes(cls): class A(_base.ComparableEntity): @@ -641,7 +641,7 @@ class UniqueColReferenceSwitchTest(_base.MappedTest): b.a = a2 session.delete(a1) session.flush() - + class RelationshipToSelectableTest(_base.MappedTest): """Test a map to a select that relates to a map to the table.""" @@ -712,9 +712,9 @@ class FKEquatedToConstantTest(_base.MappedTest): """test a relationship with a non-column entity in the primary join, is not viewonly, and also has the non-column's clause mentioned in the foreign keys list. - + """ - + @classmethod def define_tables(cls, metadata): Table('tags', metadata, Column("id", Integer, primary_key=True, @@ -753,13 +753,13 @@ class FKEquatedToConstantTest(_base.MappedTest): sess.add(t1) sess.flush() sess.expunge_all() - + # relationship works eq_( sess.query(Tag).all(), [Tag(data='some tag', foo=[TagInstance(data='iplc_case')])] ) - + # both TagInstances were persisted eq_( sess.query(TagInstance).order_by(TagInstance.data).all(), @@ -767,7 +767,7 @@ class FKEquatedToConstantTest(_base.MappedTest): ) class BackrefPropagatesForwardsArgs(_base.MappedTest): - + @classmethod def define_tables(cls, metadata): Table('users', metadata, @@ -781,17 +781,17 @@ class BackrefPropagatesForwardsArgs(_base.MappedTest): Column('user_id', Integer), Column('email', String(50)) ) - + @classmethod def setup_classes(cls): class User(_base.ComparableEntity): pass class Address(_base.ComparableEntity): pass - + @testing.resolve_artifact_names def test_backref(self): - + mapper(User, users, properties={ 'addresses':relationship(Address, primaryjoin=addresses.c.user_id==users.c.id, @@ -799,7 +799,7 @@ class BackrefPropagatesForwardsArgs(_base.MappedTest): backref='user') }) mapper(Address, addresses) - + sess = sessionmaker()() u1 = User(name='u1', addresses=[Address(email='a1')]) sess.add(u1) @@ -807,18 +807,18 @@ class BackrefPropagatesForwardsArgs(_base.MappedTest): eq_(sess.query(Address).all(), [ Address(email='a1', user=User(name='u1')) ]) - + class AmbiguousJoinInterpretedAsSelfRef(_base.MappedTest): """test ambiguous joins due to FKs on both sides treated as self-referential. - + this mapping is very similar to that of test/orm/inheritance/query.py SelfReferentialTestJoinedToBase , except that inheritance is not used here. - + """ - + @classmethod def define_tables(cls, metadata): subscriber_table = Table('subscriber', metadata, @@ -854,14 +854,14 @@ class AmbiguousJoinInterpretedAsSelfRef(_base.MappedTest): 'addresses' : relationship(Address, backref=backref("customer")) }) - + @testing.resolve_artifact_names def test_mapping(self): from sqlalchemy.orm.interfaces import ONETOMANY, MANYTOONE sess = create_session() assert Subscriber.addresses.property.direction is ONETOMANY assert Address.customer.property.direction is MANYTOONE - + s1 = Subscriber(type='A', addresses = [ Address(type='D'), @@ -869,15 +869,15 @@ class AmbiguousJoinInterpretedAsSelfRef(_base.MappedTest): ] ) a1 = Address(type='B', customer=Subscriber(type='C')) - + assert s1.addresses[0].customer is s1 assert a1.customer.addresses[0] is a1 - + sess.add_all([s1, a1]) - + sess.flush() sess.expunge_all() - + eq_( sess.query(Subscriber).order_by(Subscriber.type).all(), [ @@ -892,24 +892,24 @@ class ManualBackrefTest(_fixtures.FixtureTest): """Test explicit relationships that are backrefs to each other.""" run_inserts = None - + @testing.resolve_artifact_names def test_o2m(self): mapper(User, users, properties={ 'addresses':relationship(Address, back_populates='user') }) - + mapper(Address, addresses, properties={ 'user':relationship(User, back_populates='addresses') }) - + sess = create_session() - + u1 = User(name='u1') a1 = Address(email_address='foo') u1.addresses.append(a1) assert a1.user is u1 - + sess.add(u1) sess.flush() sess.expire_all() @@ -922,33 +922,33 @@ class ManualBackrefTest(_fixtures.FixtureTest): mapper(User, users, properties={ 'addresses':relationship(Address, back_populates='userr') }) - + mapper(Address, addresses, properties={ 'user':relationship(User, back_populates='addresses') }) - + assert_raises(sa.exc.InvalidRequestError, configure_mappers) - + @testing.resolve_artifact_names def test_invalid_target(self): mapper(User, users, properties={ 'addresses':relationship(Address, back_populates='dingaling'), }) - + mapper(Dingaling, dingalings) mapper(Address, addresses, properties={ 'dingaling':relationship(Dingaling) }) - + assert_raises_message(sa.exc.ArgumentError, r"reverse_property 'dingaling' on relationship " "User.addresses references " "relationship Address.dingaling, which does not " "reference mapper Mapper\|User\|users", configure_mappers) - + class JoinConditionErrorTest(testing.TestBase): - + def test_clauseelement_pj(self): from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() @@ -960,7 +960,7 @@ class JoinConditionErrorTest(testing.TestBase): id = Column('id', Integer, primary_key=True) c1id = Column('c1id', Integer, ForeignKey('c1.id')) c2 = relationship(C1, primaryjoin=C1.id) - + assert_raises(sa.exc.ArgumentError, configure_mappers) def test_clauseelement_pj_false(self): @@ -976,7 +976,7 @@ class JoinConditionErrorTest(testing.TestBase): c2 = relationship(C1, primaryjoin="x"=="y") assert_raises(sa.exc.ArgumentError, configure_mappers) - + def test_only_column_elements(self): m = MetaData() t1 = Table('t1', m, @@ -991,15 +991,15 @@ class JoinConditionErrorTest(testing.TestBase): class C2(object): pass - mapper(C1, t1, properties={'c2':relationship(C2, + mapper(C1, t1, properties={'c2':relationship(C2, primaryjoin=t1.join(t2))}) mapper(C2, t2) assert_raises(sa.exc.ArgumentError, configure_mappers) - + def test_invalid_string_args(self): from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import util - + for argname, arg in [ ('remote_side', ['c1.id']), ('remote_side', ['id']), @@ -1013,21 +1013,21 @@ class JoinConditionErrorTest(testing.TestBase): class C1(Base): __tablename__ = 'c1' id = Column('id', Integer, primary_key=True) - + class C2(Base): __tablename__ = 'c2' id_ = Column('id', Integer, primary_key=True) c1id = Column('c1id', Integer, ForeignKey('c1.id')) c2 = relationship(C1, **kw) - + assert_raises_message( sa.exc.ArgumentError, "Column-based expression object expected " "for argument '%s'; got: '%s', type %r" % (argname, arg[0], type(arg[0])), configure_mappers) - - + + def test_fk_error_raised(self): m = MetaData() t1 = Table('t1', m, @@ -1042,17 +1042,17 @@ class JoinConditionErrorTest(testing.TestBase): Column('id', Integer, primary_key=True), Column('t1id', Integer, ForeignKey('t1.id')) ) - + class C1(object): pass class C2(object): pass - + mapper(C1, t1, properties={'c2':relationship(C2)}) mapper(C2, t3) - + assert_raises(sa.exc.NoReferencedColumnError, configure_mappers) - + def test_join_error_raised(self): m = MetaData() t1 = Table('t1', m, @@ -1076,10 +1076,10 @@ class JoinConditionErrorTest(testing.TestBase): mapper(C2, t3) assert_raises(sa.exc.ArgumentError, configure_mappers) - + def teardown(self): - clear_mappers() - + clear_mappers() + class TypeMatchTest(_base.MappedTest): """test errors raised when trying to add items whose type is not handled by a relationship""" @@ -1273,18 +1273,18 @@ class ViewOnlyM2MBackrefTest(_base.MappedTest): Column('t1id', Integer, ForeignKey('t1.id'), primary_key=True), Column('t2id', Integer, ForeignKey('t2.id'), primary_key=True), ) - + @testing.resolve_artifact_names def test_viewonly(self): class A(_base.ComparableEntity):pass class B(_base.ComparableEntity):pass - + mapper(A, t1, properties={ 'bs':relationship(B, secondary=t1t2, backref=backref('as_', viewonly=True)) }) mapper(B, t2) - + sess = create_session() a1 = A() b1 = B(as_=[a1]) @@ -1297,7 +1297,7 @@ class ViewOnlyM2MBackrefTest(_base.MappedTest): eq_( sess.query(B).first(), B(as_=[A(id=a1.id)]) ) - + class ViewOnlyOverlappingNames(_base.MappedTest): """'viewonly' mappings with overlapping PK column names.""" @@ -1425,10 +1425,10 @@ class ViewOnlyUniqueNames(_base.MappedTest): class ViewOnlyLocalRemoteM2M(testing.TestBase): """test that local-remote is correctly determined for m2m""" - + def test_local_remote(self): meta = MetaData() - + t1 = Table('t1', meta, Column('id', Integer, primary_key=True), ) @@ -1439,7 +1439,7 @@ class ViewOnlyLocalRemoteM2M(testing.TestBase): Column('t1_id', Integer, ForeignKey('t1.id',)), Column('t2_id', Integer, ForeignKey('t2.id',)), ) - + class A(object): pass class B(object): pass mapper( B, t2, ) @@ -1453,8 +1453,8 @@ class ViewOnlyLocalRemoteM2M(testing.TestBase): m.get_property('b_plain').local_remote_pairs == \ [(t1.c.id, t12.c.t1_id), (t2.c.id, t12.c.t2_id)] - - + + class ViewOnlyNonEquijoin(_base.MappedTest): """'viewonly' mappings based on non-equijoins.""" @@ -1878,7 +1878,7 @@ class InvalidRemoteSideTest(_base.MappedTest): "mean to set remote_side on the many-to-one side ?", configure_mappers) - + class InvalidRelationshipEscalationTest(_base.MappedTest): @classmethod @@ -2041,8 +2041,8 @@ class InvalidRelationshipEscalationTest(_base.MappedTest): sa.exc.ArgumentError, "could not determine any local/remote column pairs", sa.orm.configure_mappers) - - + + @testing.resolve_artifact_names def test_no_equated_self_ref(self): mapper(Foo, foos, properties={ @@ -2093,7 +2093,7 @@ class InvalidRelationshipEscalationTest(_base.MappedTest): viewonly=True)}) mapper(Bar, bars_with_fks) sa.orm.configure_mappers() - + @testing.resolve_artifact_names def test_no_equated_self_ref_viewonly(self): mapper(Foo, foos, properties={ @@ -2111,7 +2111,7 @@ class InvalidRelationshipEscalationTest(_base.MappedTest): "present, or are otherwise part of a " "ForeignKeyConstraint on their parent " "Table.", sa.orm.configure_mappers) - + sa.orm.clear_mappers() mapper(Foo, foos_with_fks, properties={ 'foos':relationship(Foo, @@ -2162,7 +2162,7 @@ class InvalidRelationshipEscalationTest(_base.MappedTest): "Could not determine relationship direction for primaryjoin " "condition", configure_mappers) - + @testing.resolve_artifact_names def test_equated_self_ref_wrong_fks(self): @@ -2243,7 +2243,7 @@ class InvalidRelationshipEscalationTestM2M(_base.MappedTest): primaryjoin=foos.c.id==foobars.c.fid, secondaryjoin=foobars.c.bid==bars.c.id)}) mapper(Bar, bars) - + assert_raises_message(sa.exc.SAWarning, "No ForeignKey objects were present in " "secondary table 'foobars'. Assumed " @@ -2252,7 +2252,7 @@ class InvalidRelationshipEscalationTestM2M(_base.MappedTest): "condition 'foos.id = foobars.fid' on " "relationship Foo.bars", sa.orm.configure_mappers) - + sa.orm.clear_mappers() mapper(Foo, foos, properties={ 'bars': relationship(Bar, @@ -2314,8 +2314,8 @@ class InvalidRelationshipEscalationTestM2M(_base.MappedTest): Foo.bars.property.secondary_synchronize_pairs, [(bars.c.id, foobars_with_many_columns.c.bid)] ) - - + + @testing.resolve_artifact_names def test_bad_primaryjoin(self): mapper(Foo, foos, properties={ @@ -2330,7 +2330,7 @@ class InvalidRelationshipEscalationTestM2M(_base.MappedTest): "Could not determine relationship direction for " "primaryjoin condition", configure_mappers) - + sa.orm.clear_mappers() mapper(Foo, foos, properties={ 'bars': relationship(Bar, @@ -2360,7 +2360,7 @@ class InvalidRelationshipEscalationTestM2M(_base.MappedTest): viewonly=True)}) mapper(Bar, bars) sa.orm.configure_mappers() - + @testing.resolve_artifact_names def test_bad_secondaryjoin(self): mapper(Foo, foos, properties={ @@ -2404,22 +2404,22 @@ class InvalidRelationshipEscalationTestM2M(_base.MappedTest): class ActiveHistoryFlagTest(_fixtures.FixtureTest): run_inserts = None run_deletes = None - + def _test_attribute(self, obj, attrname, newvalue): sess = Session() sess.add(obj) oldvalue = getattr(obj, attrname) sess.commit() - + # expired assert attrname not in obj.__dict__ - + setattr(obj, attrname, newvalue) eq_( attributes.get_history(obj, attrname), ([newvalue,], (), [oldvalue,]) ) - + @testing.resolve_artifact_names def test_column_property_flag(self): mapper(User, users, properties={ @@ -2439,7 +2439,7 @@ class ActiveHistoryFlagTest(_fixtures.FixtureTest): u2 = User(name='ed') a1 = Address(email_address='a1', user=u1) self._test_attribute(a1, 'user', u2) - + @testing.resolve_artifact_names def test_composite_property_flag(self): class MyComposite(object): @@ -2460,12 +2460,12 @@ class ActiveHistoryFlagTest(_fixtures.FixtureTest): }) o1 = Order(composite=MyComposite('foo', 1)) self._test_attribute(o1, "composite", MyComposite('bar', 1)) - - + + class RelationDeprecationTest(_base.MappedTest): """test usage of the old 'relation' function.""" - + run_inserts = 'once' run_deletes = None diff --git a/test/orm/test_scoping.py b/test/orm/test_scoping.py index 43472eae3..2ea1960f1 100644 --- a/test/orm/test_scoping.py +++ b/test/orm/test_scoping.py @@ -78,7 +78,7 @@ class ScopedSessionTest(_base.MappedTest): def test_config_errors(self): Session = scoped_session(sa.orm.sessionmaker()) - + s = Session() assert_raises_message( sa.exc.InvalidRequestError, @@ -91,6 +91,6 @@ class ScopedSessionTest(_base.MappedTest): "At least one scoped session is already present. ", Session.configure, bind=testing.db ) - + diff --git a/test/orm/test_selectable.py b/test/orm/test_selectable.py index 54d0980a0..d1cf29751 100644 --- a/test/orm/test_selectable.py +++ b/test/orm/test_selectable.py @@ -46,12 +46,12 @@ class SelectableNoFromsTest(_base.MappedTest, AssertsCompiledSQL): "could not assemble any primary key columns", mapper, Subset, selectable ) - + @testing.resolve_artifact_names def test_no_selects(self): subset_select = select([common.c.id, common.c.data]) assert_raises(sa.exc.InvalidRequestError, mapper, Subset, subset_select) - + @testing.resolve_artifact_names def test_basic(self): subset_select = select([common.c.id, common.c.data]).alias() diff --git a/test/orm/test_session.py b/test/orm/test_session.py index d8b9b073a..ab0251368 100644 --- a/test/orm/test_session.py +++ b/test/orm/test_session.py @@ -78,7 +78,7 @@ class SessionTest(_fixtures.FixtureTest): object_session, User() ) - + @testing.requires.sequences def test_sequence_execute(self): seq = Sequence("some_sequence") @@ -88,8 +88,8 @@ class SessionTest(_fixtures.FixtureTest): eq_(sess.execute(seq), 1) finally: seq.drop(testing.db) - - + + @testing.resolve_artifact_names def test_expunge_cascade(self): mapper(Address, addresses) @@ -152,7 +152,7 @@ class SessionTest(_fixtures.FixtureTest): sess.execute(users_unbound.delete()) eq_(sess.execute(users_unbound.select()).fetchall(), []) - + sess.close() @engines.close_open_connections @@ -256,7 +256,7 @@ class SessionTest(_fixtures.FixtureTest): sess = create_session() sess.add(User(name='test')) sess.flush() - + u1 = sess.query(User).first() make_transient(u1) assert u1 not in sess @@ -268,7 +268,7 @@ class SessionTest(_fixtures.FixtureTest): make_transient(u1) sess.add(u1) assert u1 in sess.new - + # test expired attributes # get unexpired u1 = sess.query(User).first() @@ -279,9 +279,9 @@ class SessionTest(_fixtures.FixtureTest): # works twice make_transient(u1) - + sess.close() - + u1.name = 'test2' sess.add(u1) sess.flush() @@ -289,7 +289,7 @@ class SessionTest(_fixtures.FixtureTest): sess.delete(u1) sess.flush() assert u1 not in sess - + assert_raises(sa.exc.InvalidRequestError, sess.add, u1) make_transient(u1) sess.add(u1) @@ -299,37 +299,37 @@ class SessionTest(_fixtures.FixtureTest): @testing.resolve_artifact_names def test_deleted_flag(self): mapper(User, users) - + sess = sessionmaker()() - + u1 = User(name='u1') sess.add(u1) sess.commit() - + sess.delete(u1) sess.flush() assert u1 not in sess assert_raises(sa.exc.InvalidRequestError, sess.add, u1) sess.rollback() assert u1 in sess - + sess.delete(u1) sess.commit() assert u1 not in sess assert_raises(sa.exc.InvalidRequestError, sess.add, u1) - + make_transient(u1) sess.add(u1) sess.commit() - + eq_(sess.query(User).count(), 1) - + @testing.resolve_artifact_names def test_autoflush_expressions(self): """test that an expression which is dependent on object state is evaluated after the session autoflushes. This is the lambda inside of strategies.py lazy_clause. - + """ mapper(User, users, properties={ 'addresses':relationship(Address, backref="user")}) @@ -419,7 +419,7 @@ class SessionTest(_fixtures.FixtureTest): assert newad not in u.addresses # pending objects dont get expired assert newad.email_address == 'a new address' - + @testing.resolve_artifact_names def test_autocommit_doesnt_raise_on_pending(self): mapper(User, users) @@ -430,7 +430,7 @@ class SessionTest(_fixtures.FixtureTest): session.begin() session.flush() session.commit() - + def test_active_flag(self): sess = create_session(bind=config.db, autocommit=True) assert not sess.is_active @@ -438,7 +438,7 @@ class SessionTest(_fixtures.FixtureTest): assert sess.is_active sess.rollback() assert not sess.is_active - + @testing.resolve_artifact_names def test_textual_execute(self): """test that Session.execute() converts to text()""" @@ -525,15 +525,15 @@ class SessionTest(_fixtures.FixtureTest): def test_transactions_isolated(self): mapper(User, users) users.delete().execute() - + s1 = create_session(bind=testing.db, autocommit=False) s2 = create_session(bind=testing.db, autocommit=False) u1 = User(name='u1') s1.add(u1) s1.flush() - + assert s2.query(User).all() == [] - + @testing.requires.two_phase_transactions @testing.resolve_artifact_names def test_twophase(self): @@ -727,7 +727,7 @@ class SessionTest(_fixtures.FixtureTest): sa.exc.DBAPIError, sess.commit ) - + for i in range(5): assert_raises_message(sa.exc.InvalidRequestError, "^This Session's transaction has been " @@ -740,8 +740,8 @@ class SessionTest(_fixtures.FixtureTest): sess.rollback() sess.add(User(id=5, name='some name')) sess.commit() - - + + @testing.resolve_artifact_names def test_no_autocommit_with_explicit_commit(self): mapper(User, users) @@ -861,7 +861,7 @@ class SessionTest(_fixtures.FixtureTest): assert user not in s s.delete(user) assert user in s - + s.flush() assert user not in s assert s.query(User).count() == 0 @@ -959,17 +959,17 @@ class SessionTest(_fixtures.FixtureTest): del user s.add(u2) - + del u2 gc_collect() - + assert len(s.identity_map) == 1 assert len(s.dirty) == 1 assert None not in s.dirty s.flush() gc_collect() assert not s.dirty - + assert not s.identity_map @testing.resolve_artifact_names @@ -990,8 +990,8 @@ class SessionTest(_fixtures.FixtureTest): assert_raises(AssertionError, s.identity_map.add, sa.orm.attributes.instance_state(u2)) - - + + @testing.resolve_artifact_names def test_weakref_with_cycles_o2m(self): s = sessionmaker()() @@ -1001,11 +1001,11 @@ class SessionTest(_fixtures.FixtureTest): mapper(Address, addresses) s.add(User(name="ed", addresses=[Address(email_address="ed1")])) s.commit() - + user = s.query(User).options(joinedload(User.addresses)).one() user.addresses[0].user # lazyload eq_(user, User(name="ed", addresses=[Address(email_address="ed1")])) - + del user gc_collect() assert len(s.identity_map) == 0 @@ -1016,11 +1016,11 @@ class SessionTest(_fixtures.FixtureTest): del user gc_collect() assert len(s.identity_map) == 2 - + s.commit() user = s.query(User).options(joinedload(User.addresses)).one() eq_(user, User(name="ed", addresses=[Address(email_address="ed2")])) - + @testing.resolve_artifact_names def test_weakref_with_cycles_o2o(self): s = sessionmaker()() @@ -1046,11 +1046,11 @@ class SessionTest(_fixtures.FixtureTest): del user gc_collect() assert len(s.identity_map) == 2 - + s.commit() user = s.query(User).options(joinedload(User.address)).one() eq_(user, User(name="ed", address=Address(email_address="ed2"))) - + @testing.resolve_artifact_names def test_strong_ref(self): s = create_session(weak_identity_map=False) @@ -1071,7 +1071,7 @@ class SessionTest(_fixtures.FixtureTest): assert s.identity_map._modified s.flush() eq_(users.select().execute().fetchall(), [(user.id, 'u2')]) - + @testing.fails_on('+zxjdbc', 'http://www.sqlalchemy.org/trac/ticket/1473') @testing.resolve_artifact_names def test_prune(self): @@ -1198,10 +1198,10 @@ class SessionTest(_fixtures.FixtureTest): mapper(User, users) sess = Session() - + sess.add_all([User(name='u1'), User(name='u2'), User(name='u3')]) sess.commit() - + u1, u2, u3 = sess.query(User).all() for i, (key, value) in enumerate(sess.identity_map.iteritems()): if i == 2: @@ -1212,7 +1212,7 @@ class DisposedStates(_base.MappedTest): run_setup_mappers = 'once' run_inserts = 'once' run_deletes = None - + @classmethod def define_tables(cls, metadata): global t1 @@ -1227,25 +1227,25 @@ class DisposedStates(_base.MappedTest): def __init__(self, data): self.data = data mapper(T, t1) - + def teardown(self): from sqlalchemy.orm.session import _sessions _sessions.clear() super(DisposedStates, self).teardown() - + def _set_imap_in_disposal(self, sess, *objs): """remove selected objects from the given session, as though they were dereferenced and removed from WeakIdentityMap. - + Hardcodes the identity map's "all_states()" method to return the full list of states. This simulates the all_states() method returning results, afterwhich some of the states get garbage collected (this normally only happens during asynchronous gc). The Session now has one or more InstanceState's which have been removed from the identity map and disposed. - + Will the Session not trip over this ??? Stay tuned. - + """ all_states = sess.identity_map.all_states() @@ -1254,7 +1254,7 @@ class DisposedStates(_base.MappedTest): state = attributes.instance_state(obj) sess.identity_map.remove(state) state.dispose() - + def _test_session(self, **kwargs): global sess sess = create_session(**kwargs) @@ -1268,32 +1268,32 @@ class DisposedStates(_base.MappedTest): o1.data = 't1modified' o5.data = 't5modified' - + self._set_imap_in_disposal(sess, o2, o4, o5) return sess - + def test_flush(self): self._test_session().flush() - + def test_clear(self): self._test_session().expunge_all() - + def test_close(self): self._test_session().close() - + def test_expunge_all(self): self._test_session().expunge_all() - + def test_expire_all(self): self._test_session().expire_all() - + def test_rollback(self): sess = self._test_session(autocommit=False, expire_on_commit=True) sess.commit() - + sess.rollback() - - + + class SessionInterface(testing.TestBase): """Bogus args to Session methods produce actionable exceptions.""" diff --git a/test/orm/test_subquery_relations.py b/test/orm/test_subquery_relations.py index 2aadf26d4..b306dcbba 100644 --- a/test/orm/test_subquery_relations.py +++ b/test/orm/test_subquery_relations.py @@ -14,7 +14,7 @@ import sqlalchemy as sa class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): run_inserts = 'once' run_deletes = None - + @testing.resolve_artifact_names def test_basic(self): mapper(User, users, properties={ @@ -23,18 +23,18 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): order_by=Address.id) }) sess = create_session() - + q = sess.query(User).options(subqueryload(User.addresses)) - + def go(): eq_( [User(id=7, addresses=[ Address(id=1, email_address='jack@bean.com')])], q.filter(User.id==7).all() ) - + self.assert_sql_count(testing.db, go, 2) - + def go(): eq_( self.static.user_address_result, @@ -54,9 +54,9 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): order_by=Address.id) }) sess = create_session() - + u = aliased(User) - + q = sess.query(u).options(subqueryload(u.addresses)) def go(): @@ -74,10 +74,10 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): q.order_by(u.id).all() ) self.assert_sql_count(testing.db, go, 2) - + q = sess.query(u).\ options(subqueryload_all(u.addresses, Address.dingalings)) - + def go(): eq_( [ @@ -93,8 +93,8 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): q.filter(u.id.in_([8, 9])).all() ) self.assert_sql_count(testing.db, go, 3) - - + + @testing.resolve_artifact_names def test_from_get(self): mapper(User, users, properties={ @@ -103,7 +103,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): order_by=Address.id) }) sess = create_session() - + q = sess.query(User).options(subqueryload(User.addresses)) def go(): eq_( @@ -111,7 +111,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): Address(id=1, email_address='jack@bean.com')]), q.get(7) ) - + self.assert_sql_count(testing.db, go, 2) @testing.resolve_artifact_names @@ -132,7 +132,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): ) self.assert_sql_count(testing.db, go, 2) - + @testing.resolve_artifact_names def test_disable_dynamic(self): """test no subquery option on a dynamic.""" @@ -142,7 +142,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): }) mapper(Address, addresses) sess = create_session() - + # previously this would not raise, but would emit # the query needlessly and put the result nowhere. assert_raises_message( @@ -150,7 +150,7 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): "User.addresses' does not support object population - eager loading cannot be applied.", sess.query(User).options(subqueryload(User.addresses)).first, ) - + @testing.resolve_artifact_names def test_many_to_many(self): mapper(Keyword, keywords) @@ -290,10 +290,10 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): def test_options_pathing(self): self._do_options_test(self._pathing_runs) - + def test_mapper_pathing(self): self._do_mapper_test(self._pathing_runs) - + @testing.resolve_artifact_names def _do_options_test(self, configs): mapper(User, users, properties={ @@ -309,12 +309,12 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): order_by=keywords.c.id) #m2m }) mapper(Keyword, keywords) - + callables = { 'joinedload':joinedload, 'subqueryload':subqueryload } - + for o, i, k, count in configs: options = [] if o in callables: @@ -349,12 +349,12 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): order_by=keywords.c.id) }) mapper(Keyword, keywords) - + try: self._do_query_tests([], count) finally: clear_mappers() - + @testing.resolve_artifact_names def _do_query_tests(self, opts, count): sess = create_session() @@ -378,8 +378,8 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): order_by(User.id).all(), self.static.user_item_keyword_result[0:1] ) - - + + @testing.resolve_artifact_names def test_cyclical(self): """A circular eager relationship breaks the cycle with a lazy loader""" @@ -710,7 +710,7 @@ class SelfReferentialTest(_base.MappedTest): n2.append(Node(data='n21')) n2.children[0].append(Node(data='n211')) n2.children[0].append(Node(data='n212')) - + sess.add(n1) sess.add(n2) sess.flush() @@ -890,4 +890,4 @@ class SelfReferentialTest(_base.MappedTest): ], d) self.assert_sql_count(testing.db, go, 4) - + diff --git a/test/orm/test_transaction.py b/test/orm/test_transaction.py index 9cb9604a7..d27bf1af2 100644 --- a/test/orm/test_transaction.py +++ b/test/orm/test_transaction.py @@ -23,10 +23,10 @@ class TransactionTest(FixtureTest): }) mapper(Address, addresses) - + class FixtureDataTest(TransactionTest): run_inserts = 'each' - + def test_attrs_on_rollback(self): sess = self.session() u1 = sess.query(User).get(7) @@ -93,13 +93,13 @@ class AutoExpireTest(TransactionTest): s.rollback() assert u1 in s assert u1 not in s.deleted - + def test_gced_delete_on_rollback(self): s = self.session() u1 = User(name='ed') s.add(u1) s.commit() - + s.delete(u1) u1_state = attributes.instance_state(u1) assert u1_state in s.identity_map.all_states() @@ -110,7 +110,7 @@ class AutoExpireTest(TransactionTest): del u1 gc_collect() assert u1_state.obj() is None - + s.rollback() assert u1_state in s.identity_map.all_states() u1 = s.query(User).filter_by(name='ed').one() @@ -120,7 +120,7 @@ class AutoExpireTest(TransactionTest): s.flush() assert s.scalar(users.count()) == 0 s.commit() - + def test_trans_deleted_cleared_on_rollback(self): s = self.session() u1 = User(name='ed') @@ -189,14 +189,14 @@ class TwoPhaseTest(TransactionTest): @testing.requires.two_phase_transactions def test_rollback_on_prepare(self): s = self.session(twophase=True) - + u = User(name='ed') s.add(u) s.prepare() s.rollback() - + assert u not in s - + class RollbackRecoverTest(TransactionTest): def test_pk_violation(self): @@ -416,7 +416,7 @@ class AccountingFlagsTest(TransactionTest): sess.commit() testing.db.execute(users.update(users.c.name=='ed').values(name='edward')) - + assert u1.name == 'ed' sess.expire_all() assert u1.name == 'edward' @@ -429,7 +429,7 @@ class AccountingFlagsTest(TransactionTest): u1.name = 'edwardo' sess.rollback() - + testing.db.execute(users.update(users.c.name=='ed').values(name='edward')) assert u1.name == 'edwardo' @@ -449,30 +449,30 @@ class AccountingFlagsTest(TransactionTest): assert u1.name == 'edwardo' sess.commit() - + assert testing.db.execute(select([users.c.name])).fetchall() == [('edwardo',)] assert u1.name == 'edwardo' sess.delete(u1) sess.commit() - + def test_preflush_no_accounting(self): sess = sessionmaker(_enable_transaction_accounting=False, autocommit=True)() u1 = User(name='ed') sess.add(u1) sess.flush() - + sess.begin() u1.name = 'edwardo' u2 = User(name="some other user") sess.add(u2) - + sess.rollback() sess.begin() assert testing.db.execute(select([users.c.name])).fetchall() == [('ed',)] - - + + class AutoCommitTest(TransactionTest): def test_begin_nested_requires_trans(self): sess = create_session(autocommit=True) @@ -483,7 +483,7 @@ class AutoCommitTest(TransactionTest): u1 = User(name='ed') sess.add(u1) - + sess.begin() u2 = User(name='some other user') sess.add(u2) @@ -533,7 +533,7 @@ class NaturalPKRollbackTest(_base.MappedTest): session.rollback() - - + + diff --git a/test/orm/test_unitofwork.py b/test/orm/test_unitofwork.py index e85166f68..d5cd46916 100644 --- a/test/orm/test_unitofwork.py +++ b/test/orm/test_unitofwork.py @@ -64,7 +64,7 @@ class UnicodeTest(_base.MappedTest): uni_type = VARCHAR(50, collation='utf8_unicode_ci') else: uni_type = sa.Unicode(50) - + Table('uni_t1', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), @@ -94,7 +94,7 @@ class UnicodeTest(_base.MappedTest): session.commit() self.assert_(t1.txt == txt) - + @testing.resolve_artifact_names def test_relationship(self): mapper(Test, uni_t1, properties={ @@ -226,17 +226,17 @@ class BinaryHistTest(_base.MappedTest, testing.AssertsExecutionResults): @testing.resolve_artifact_names def test_binary_equality(self): - + # Py3K #data = b"this is some data" # Py2K data = "this is some data" # end Py2K - + mapper(Foo, t1) - + s = create_session() - + f1 = Foo(data=data) s.add(f1) s.flush() @@ -251,8 +251,8 @@ class BinaryHistTest(_base.MappedTest, testing.AssertsExecutionResults): def go(): s.flush() self.assert_sql_count(testing.db, go, 0) - - + + @@ -491,12 +491,12 @@ class PassiveDeletesTest(_base.MappedTest): assert mytable.count().scalar() == 0 assert myothertable.count().scalar() == 0 - + @testing.emits_warning(r".*'passive_deletes' is normally configured on one-to-many") @testing.resolve_artifact_names def test_backwards_pd(self): """Test that passive_deletes=True disables a delete from an m2o. - + This is not the usual usage and it now raises a warning, but test that it works nonetheless. @@ -505,7 +505,7 @@ class PassiveDeletesTest(_base.MappedTest): 'myclass':relationship(MyClass, cascade="all, delete", passive_deletes=True) }) mapper(MyClass, mytable) - + session = create_session() mc = MyClass() mco = MyOtherClass() @@ -515,15 +515,15 @@ class PassiveDeletesTest(_base.MappedTest): assert mytable.count().scalar() == 1 assert myothertable.count().scalar() == 1 - + session.expire(mco, ['myclass']) session.delete(mco) session.flush() - + # mytable wasn't deleted, is the point. assert mytable.count().scalar() == 1 assert myothertable.count().scalar() == 0 - + @testing.resolve_artifact_names def test_aaa_m2o_emits_warning(self): mapper(MyOtherClass, myothertable, properties={ @@ -531,7 +531,7 @@ class PassiveDeletesTest(_base.MappedTest): }) mapper(MyClass, mytable) assert_raises(sa.exc.SAWarning, sa.orm.configure_mappers) - + class ExtraPassiveDeletesTest(_base.MappedTest): __requires__ = ('foreign_keys',) @@ -628,19 +628,19 @@ class ColumnCollisionTest(_base.MappedTest): Column('book_id', String(50)), Column('title', String(50)) ) - + @testing.resolve_artifact_names def test_naming(self): class Book(_base.ComparableEntity): pass - + mapper(Book, book) sess = create_session() - + b1 = Book(book_id='abc', title='def') sess.add(b1) sess.flush() - + b1.title = 'ghi' sess.flush() sess.close() @@ -648,9 +648,9 @@ class ColumnCollisionTest(_base.MappedTest): sess.query(Book).first(), Book(book_id='abc', title='ghi') ) - - - + + + class DefaultTest(_base.MappedTest): """Exercise mappings on columns with DefaultGenerators. @@ -847,12 +847,12 @@ class ColumnPropertyTest(_base.MappedTest): Column('id', Integer, ForeignKey('data.id'), primary_key=True), Column('c', String(50)), ) - + @classmethod def setup_mappers(cls): class Data(_base.BasicEntity): pass - + @testing.resolve_artifact_names def test_refreshes(self): mapper(Data, data, properties={ @@ -865,7 +865,7 @@ class ColumnPropertyTest(_base.MappedTest): m = mapper(Data, data) m.add_property('aplusb', column_property(data.c.a + literal_column("' '") + data.c.b)) self._test() - + @testing.resolve_artifact_names def test_with_inheritance(self): class SubData(Data): @@ -874,32 +874,32 @@ class ColumnPropertyTest(_base.MappedTest): 'aplusb':column_property(data.c.a + literal_column("' '") + data.c.b) }) mapper(SubData, subdata, inherits=Data) - + sess = create_session() sd1 = SubData(a="hello", b="there", c="hi") sess.add(sd1) sess.flush() eq_(sd1.aplusb, "hello there") - + @testing.resolve_artifact_names def _test(self): sess = create_session() - + d1 = Data(a="hello", b="there") sess.add(d1) sess.flush() - + eq_(d1.aplusb, "hello there") - + d1.b = "bye" sess.flush() eq_(d1.aplusb, "hello bye") - + d1.b = 'foobar' d1.aplusb = 'im setting this explicitly' sess.flush() eq_(d1.aplusb, "im setting this explicitly") - + class OneToManyTest(_fixtures.FixtureTest): run_inserts = None @@ -1372,29 +1372,29 @@ class SaveTest(_fixtures.FixtureTest): assert instance is self.current_instance mapper(User, users, batch=False) - + evt = Events() event.listen(User, "before_insert", evt.before_insert) event.listen(User, "after_insert", evt.after_insert) - + u1 = User(name='user1') u2 = User(name='user2') session = create_session() session.add_all((u1, u2)) session.flush() - + u3 = User(name='user3') u4 = User(name='user4') u5 = User(name='user5') - + session.add_all([u4, u5, u3]) session.flush() - + # test insert ordering is maintained assert names == ['user1', 'user2', 'user4', 'user5', 'user3'] session.expunge_all() - + sa.orm.clear_mappers() m = mapper(User, users) @@ -1930,14 +1930,14 @@ class BooleanColTest(_base.MappedTest): class DontAllowFlushOnLoadingObjectTest(_base.MappedTest): """Test that objects with NULL identity keys aren't permitted to complete a flush. - + User-defined callables that execute during a load may modify state on instances which results in their being autoflushed, before attributes are populated. If the primary key identifiers are missing, an explicit assertion is needed to check that the object doesn't go through the flush process with no net changes and gets placed in the identity map with an incorrect identity key. - + """ @classmethod def define_tables(cls, metadata): @@ -1945,7 +1945,7 @@ class DontAllowFlushOnLoadingObjectTest(_base.MappedTest): Column('id', Integer, primary_key=True), Column('data', String(30)), ) - + @testing.resolve_artifact_names def test_flush_raises(self): class T1(_base.ComparableEntity): @@ -1956,28 +1956,28 @@ class DontAllowFlushOnLoadingObjectTest(_base.MappedTest): # before 'id' was even populated, i.e. a callable # within an attribute_mapped_collection self.__dict__.pop('id', None) - + # generate a change event, perhaps this occurs because # someone wrote a broken attribute_mapped_collection that # inappropriately fires off change events when it should not, # now we're dirty self.data = 'foo bar' - + # blow away that change, so an UPDATE does not occur # (since it would break) self.__dict__.pop('data', None) - + # flush ! any lazyloader here would trigger # autoflush, for example. sess.flush() - + mapper(T1, t1) - + sess = Session() sess.add(T1(data='test', id=5)) sess.commit() sess.close() - + # make sure that invalid state doesn't get into the session # with the wrong key. If the identity key is not NULL, at least # the population process would continue after the erroneous flush @@ -1987,9 +1987,9 @@ class DontAllowFlushOnLoadingObjectTest(_base.MappedTest): 'flush is occuring at an inappropriate ' 'time, such as during a load operation.', sess.query(T1).first) - - - + + + class RowSwitchTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -2096,7 +2096,7 @@ class RowSwitchTest(_base.MappedTest): assert o5 in sess.deleted assert o5.t7s[0] in sess.deleted assert o5.t7s[1] in sess.deleted - + sess.add(o6) sess.flush() @@ -2151,17 +2151,17 @@ class InheritingRowSwitchTest(_base.MappedTest): class C(P): pass - + @testing.resolve_artifact_names def test_row_switch_no_child_table(self): mapper(P, parent) mapper(C, child, inherits=P) - + sess = create_session() c1 = C(id=1, pdata='c1', cdata='c1') sess.add(c1) sess.flush() - + # establish a row switch between c1 and c2. # c2 has no value for the "child" table c2 = C(id=1, pdata='c2') @@ -2172,7 +2172,7 @@ class InheritingRowSwitchTest(_base.MappedTest): CompiledSQL("UPDATE parent SET pdata=:pdata WHERE parent.id = :parent_id", {'pdata':'c2', 'parent_id':1} ), - + # this fires as of [ticket:1362], since we synchronzize # PK/FKs on UPDATES. c2 is new so the history shows up as # pure added, update occurs. If a future change limits the @@ -2181,8 +2181,8 @@ class InheritingRowSwitchTest(_base.MappedTest): {'pid':1, 'child_id':1} ) ) - - + + class TransactionTest(_base.MappedTest): __requires__ = ('deferrable_constraints',) diff --git a/test/orm/test_unitofworkv2.py b/test/orm/test_unitofworkv2.py index 10049175a..7018f2338 100644 --- a/test/orm/test_unitofworkv2.py +++ b/test/orm/test_unitofworkv2.py @@ -25,7 +25,7 @@ class AssertsUOW(object): for d in deleted: uow.register_object(d, isdelete=True) return uow - + def _assert_uow_size(self, session, expected @@ -51,7 +51,7 @@ class RudimentaryFlushTest(UOWTest): a1, a2 = Address(email_address='a1'), Address(email_address='a2') u1 = User(name='u1', addresses=[a1, a2]) sess.add(u1) - + self.assert_sql_execution( testing.db, sess.flush, @@ -81,7 +81,7 @@ class RudimentaryFlushTest(UOWTest): u1 = User(name='u1', addresses=[a1, a2]) sess.add(u1) sess.flush() - + sess.delete(u1) sess.delete(a1) sess.delete(a2) @@ -128,9 +128,9 @@ class RudimentaryFlushTest(UOWTest): {'id':u1.id} ), ) - + def test_many_to_one_save(self): - + mapper(User, users) mapper(Address, addresses, properties={ 'user':relationship(User) @@ -141,7 +141,7 @@ class RudimentaryFlushTest(UOWTest): a1, a2 = Address(email_address='a1', user=u1), \ Address(email_address='a2', user=u1) sess.add_all([a1, a2]) - + self.assert_sql_execution( testing.db, sess.flush, @@ -173,7 +173,7 @@ class RudimentaryFlushTest(UOWTest): Address(email_address='a2', user=u1) sess.add_all([a1, a2]) sess.flush() - + sess.delete(u1) sess.delete(a1) sess.delete(a2) @@ -233,25 +233,25 @@ class RudimentaryFlushTest(UOWTest): parent = User(name='p1') c1, c2 = Address(email_address='c1', parent=parent), \ Address(email_address='c2', parent=parent) - + session = Session() session.add_all([c1, c2]) session.add(parent) session.flush() - + pid = parent.id c1id = c1.id c2id = c2.id - + session.expire(parent) session.expire(c1) session.expire(c2) - + session.delete(c1) session.delete(c2) session.delete(parent) - + # testing that relationships # are loaded even if all ids/references are # expired @@ -291,13 +291,13 @@ class RudimentaryFlushTest(UOWTest): lambda ctx: {'id': pid} ), ) - + def test_many_to_many(self): mapper(Item, items, properties={ 'keywords':relationship(Keyword, secondary=item_keywords) }) mapper(Keyword, keywords) - + sess = create_session() k1 = Keyword(name='k1') i1 = Item(description='i1', keywords=[k1]) @@ -321,7 +321,7 @@ class RudimentaryFlushTest(UOWTest): lambda ctx:{'item_id':i1.id, 'keyword_id':k1.id} ) ) - + # test that keywords collection isn't loaded sess.expire(i1, ['keywords']) i1.description = 'i2' @@ -332,7 +332,7 @@ class RudimentaryFlushTest(UOWTest): "WHERE items.id = :items_id", lambda ctx:{'description':'i2', 'items_id':i1.id}) ) - + def test_m2o_flush_size(self): mapper(User, users) mapper(Address, addresses, properties={ @@ -389,13 +389,13 @@ class SingleCycleTest(UOWTest): n2, n3 = Node(data='n2'), Node(data='n3') n1 = Node(data='n1', children=[n2, n3]) - + sess.add(n1) - + self.assert_sql_execution( testing.db, sess.flush, - + CompiledSQL( "INSERT INTO nodes (parent_id, data) VALUES " "(:parent_id, :data)", @@ -426,7 +426,7 @@ class SingleCycleTest(UOWTest): sess.add(n1) sess.flush() - + sess.delete(n1) sess.delete(n2) sess.delete(n3) @@ -466,7 +466,7 @@ class SingleCycleTest(UOWTest): CompiledSQL("DELETE FROM nodes WHERE nodes.id = :id", lambda ctx:{'id':n1.id}) ) - + def test_many_to_one_save(self): mapper(Node, nodes, properties={ 'parent':relationship(Node, remote_side=nodes.c.id) @@ -512,7 +512,7 @@ class SingleCycleTest(UOWTest): sess.add_all([n2, n3]) sess.flush() - + sess.delete(n1) sess.delete(n2) sess.delete(n3) @@ -524,7 +524,7 @@ class SingleCycleTest(UOWTest): CompiledSQL("DELETE FROM nodes WHERE nodes.id = :id", lambda ctx: {'id':n1.id}) ) - + def test_cycle_rowswitch(self): mapper(Node, nodes, properties={ 'children':relationship(Node) @@ -540,7 +540,7 @@ class SingleCycleTest(UOWTest): n3.id = n2.id n1.children.append(n3) sess.flush() - + def test_bidirectional_mutations_one(self): mapper(Node, nodes, properties={ 'children':relationship(Node, @@ -556,11 +556,11 @@ class SingleCycleTest(UOWTest): sess.delete(n2) n1.children.append(n3) sess.flush() - + sess.delete(n1) sess.delete(n3) sess.flush() - + def test_bidirectional_multilevel_save(self): mapper(Node, nodes, properties={ 'children':relationship(Node, @@ -627,27 +627,27 @@ class SingleCycleTest(UOWTest): self._assert_uow_size(sess, 2) sess.flush() - + n1.data='jack' self._assert_uow_size(sess, 2) sess.flush() - + n2 = Node(data='foo') sess.add(n2) sess.flush() - + n1.children.append(n2) self._assert_uow_size(sess, 3) - + sess.flush() - + sess = create_session() n1 = sess.query(Node).first() n1.data='ed' self._assert_uow_size(sess, 2) - + n1.children self._assert_uow_size(sess, 2) @@ -658,25 +658,25 @@ class SingleCycleTest(UOWTest): parent = Node() c1, c2 = Node(parent=parent), Node(parent=parent) - + session = Session() session.add_all([c1, c2]) session.add(parent) session.flush() - + pid = parent.id c1id = c1.id c2id = c2.id - + session.expire(parent) session.expire(c1) session.expire(c2) - + session.delete(c1) session.delete(c2) session.delete(parent) - + # testing that relationships # are loaded even if all ids/references are # expired @@ -718,9 +718,9 @@ class SingleCycleTest(UOWTest): lambda ctx: {'id': pid} ), ) - - - + + + class SingleCyclePlusAttributeTest(_base.MappedTest, testing.AssertsExecutionResults, AssertsUOW): @classmethod @@ -731,7 +731,7 @@ class SingleCyclePlusAttributeTest(_base.MappedTest, Column('parent_id', Integer, ForeignKey('nodes.id')), Column('data', String(30)) ) - + Table('foobars', metadata, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), @@ -758,13 +758,13 @@ class SingleCyclePlusAttributeTest(_base.MappedTest, sess.add(n1) # ensure "foobars" doesn't get yanked in here self._assert_uow_size(sess, 3) - + n1.foobars.append(FooBar()) # saveupdateall/deleteall for FooBar added here, # plus processstate node.foobars # currently the "all" procs stay in pairs self._assert_uow_size(sess, 6) - + sess.flush() class SingleCycleM2MTest(_base.MappedTest, @@ -779,19 +779,19 @@ class SingleCycleM2MTest(_base.MappedTest, Column('data', String(30)), Column('favorite_node_id', Integer, ForeignKey('nodes.id')) ) - + node_to_nodes =Table('node_to_nodes', metadata, Column('left_node_id', Integer, ForeignKey('nodes.id'),primary_key=True), Column('right_node_id', Integer, ForeignKey('nodes.id'),primary_key=True), ) - + @testing.resolve_artifact_names def test_many_to_many_one(self): class Node(Base): pass - + mapper(Node, nodes, properties={ 'children':relationship(Node, secondary=node_to_nodes, primaryjoin=nodes.c.id==node_to_nodes.c.left_node_id, @@ -800,24 +800,24 @@ class SingleCycleM2MTest(_base.MappedTest, ), 'favorite':relationship(Node, remote_side=nodes.c.id) }) - + sess = create_session() n1 = Node(data='n1') n2 = Node(data='n2') n3 = Node(data='n3') n4 = Node(data='n4') n5 = Node(data='n5') - + n4.favorite = n3 n1.favorite = n5 n5.favorite = n2 - + n1.children = [n2, n3, n4] n2.children = [n3, n5] n3.children = [n5, n4] - + sess.add_all([n1, n2, n3, n4, n5]) - + # can't really assert the SQL on this easily # since there's too many ways to insert the rows. # so check the end result @@ -834,9 +834,9 @@ class SingleCycleM2MTest(_base.MappedTest, (n3.id, n5.id), (n3.id, n4.id) ]) ) - + sess.delete(n1) - + self.assert_sql_execution( testing.db, sess.flush, @@ -849,7 +849,7 @@ class SingleCycleM2MTest(_base.MappedTest, "node_to_nodes.right_node_id AND nodes.id = " "node_to_nodes.left_node_id" , lambda ctx:{u'param_1': n1.id}, - ), + ), CompiledSQL( "DELETE FROM node_to_nodes WHERE " "node_to_nodes.left_node_id = :left_node_id AND " @@ -865,15 +865,15 @@ class SingleCycleM2MTest(_base.MappedTest, lambda ctx:{'id': n1.id} ), ) - + for n in [n2, n3, n4, n5]: sess.delete(n) - + # load these collections # outside of the flush() below n4.children n5.children - + self.assert_sql_execution( testing.db, sess.flush, @@ -897,7 +897,7 @@ class SingleCycleM2MTest(_base.MappedTest, lambda ctx:[{'id': n2.id}, {'id': n3.id}] ), ) - + class RowswitchAccountingTest(_base.MappedTest): @classmethod def define_tables(cls, metadata): @@ -907,7 +907,7 @@ class RowswitchAccountingTest(_base.MappedTest): Table('child', metadata, Column('id', Integer, ForeignKey('parent.id'), primary_key=True) ) - + @testing.resolve_artifact_names def test_accounting_for_rowswitch(self): class Parent(object): @@ -923,7 +923,7 @@ class RowswitchAccountingTest(_base.MappedTest): backref="parent") }) mapper(Child, child) - + sess = create_session(autocommit=False) p1 = Parent(1) @@ -964,7 +964,7 @@ class BatchInsertsTest(_base.MappedTest, testing.AssertsExecutionResults): def test_batch_interaction(self): """test batching groups same-structured, primary key present statements together. - + """ class T(Base): pass diff --git a/test/orm/test_utils.py b/test/orm/test_utils.py index e196a9617..362b54cf0 100644 --- a/test/orm/test_utils.py +++ b/test/orm/test_utils.py @@ -215,5 +215,5 @@ class IdentityKeyTest(_fixtures.FixtureTest): row = {users.c.id: 1, users.c.name: "Frank"} key = util.identity_key(User, row=row) eq_(key, (User, (1,))) - + diff --git a/test/orm/test_versioning.py b/test/orm/test_versioning.py index 94c0efc10..9da97dc1e 100644 --- a/test/orm/test_versioning.py +++ b/test/orm/test_versioning.py @@ -26,13 +26,13 @@ _uuids = [ '782a5f04b4364a53a6fce762f48921c1', 'bef510f2420f4476a7629013ead237f5', ] - + def make_uuid(): """generate uuids even on Python 2.4 which has no 'uuid'""" return _uuids.pop(0) class VersioningTest(_base.MappedTest): - + @classmethod def define_tables(cls, metadata): Table('version_table', metadata, @@ -131,11 +131,11 @@ class VersioningTest(_base.MappedTest): @testing.resolve_artifact_names def test_bump_version(self): """test that version number can be bumped. - + Ensures that the UPDATE or DELETE is against the last committed version of version_id_col, not the modified state. - + """ mapper(Foo, version_table, version_id_col=version_table.c.version_id) @@ -148,19 +148,19 @@ class VersioningTest(_base.MappedTest): f1.version_id = 2 s1.commit() eq_(f1.version_id, 2) - + # skip an id, test that history # is honored f1.version_id = 4 f1.value = "something new" s1.commit() eq_(f1.version_id, 4) - + f1.version_id = 5 s1.delete(f1) s1.commit() eq_(s1.query(Foo).count(), 0) - + @testing.emits_warning(r'.*does not support updated rowcount') @engines.close_open_connections @testing.resolve_artifact_names @@ -189,7 +189,7 @@ class VersioningTest(_base.MappedTest): # reload it - this expires the old version first s1.refresh(f1s1, lockmode='read') - + # now assert version OK s1.query(Foo).with_lockmode('read').get(f1s1.id) @@ -216,13 +216,13 @@ class VersioningTest(_base.MappedTest): f1s2 = s2.query(Foo).get(f1s1.id) s2.refresh(f1s2, lockmode='update') f1s2.value='f1 new value' - + assert_raises( exc.DBAPIError, s1.refresh, f1s1, lockmode='update_nowait' ) s1.rollback() - + s2.commit() s1.refresh(f1s1, lockmode='update_nowait') assert f1s1.version_id == f1s2.version_id @@ -281,16 +281,16 @@ class RowSwitchTest(_base.MappedTest): session.add(P(id='P1', data='P version 1')) session.commit() session.close() - + p = session.query(P).first() session.delete(p) session.add(P(id='P1', data="really a row-switch")) session.commit() - + @testing.resolve_artifact_names def test_child_row_switch(self): assert P.c.property.strategy.use_get - + session = sessionmaker()() session.add(P(id='P1', data='P version 1')) session.commit() @@ -369,27 +369,27 @@ class AlternateGeneratorTest(_base.MappedTest): @testing.resolve_artifact_names def test_child_row_switch_two(self): Session = sessionmaker() - + # TODO: not sure this test is # testing exactly what its looking for - + sess1 = Session() sess1.add(P(id='P1', data='P version 1')) sess1.commit() sess1.close() - + p1 = sess1.query(P).first() sess2 = Session() p2 = sess2.query(P).first() - + sess1.delete(p1) sess1.commit() - + # this can be removed and it still passes sess1.add(P(id='P1', data='P version 2')) sess1.commit() - + p2.data = 'P overwritten by concurrent tx' assert_raises_message( orm.exc.StaleDataError, @@ -397,12 +397,12 @@ class AlternateGeneratorTest(_base.MappedTest): r"1 row\(s\); 0 were matched.", sess2.commit ) - + class InheritanceTwoVersionIdsTest(_base.MappedTest): """Test versioning where both parent/child table have a versioning column. - + """ @classmethod def define_tables(cls, metadata): @@ -454,7 +454,7 @@ class InheritanceTwoVersionIdsTest(_base.MappedTest): # base is populated eq_(select([base.c.version_id]).scalar(), 1) - + @testing.resolve_artifact_names def test_sub_only(self): mapper(Base, base) @@ -471,12 +471,12 @@ class InheritanceTwoVersionIdsTest(_base.MappedTest): # base is not eq_(select([base.c.version_id]).scalar(), None) - + @testing.resolve_artifact_names def test_mismatch_version_col_warning(self): mapper(Base, base, version_id_col=base.c.version_id) - + assert_raises_message( exc.SAWarning, "Inheriting version_id_col 'version_id' does not " @@ -487,4 +487,3 @@ class InheritanceTwoVersionIdsTest(_base.MappedTest): mapper, Sub, sub, inherits=Base, version_id_col=sub.c.version_id) -
\ No newline at end of file diff --git a/test/perf/README b/test/perf/README index dfb6df2cc..1d03cb5ce 100644 --- a/test/perf/README +++ b/test/perf/README @@ -14,4 +14,4 @@ Current automated stress and performance tests are in test/aaa_profiling/, which test either for expected function call count, or flat growth in memory usage over time. These tests are part of the automated test suite and are maintained for 100% success rate along Python versions from 2.4 through -current 3 versions.
\ No newline at end of file +current 3 versions.
\ No newline at end of file diff --git a/test/perf/objselectspeed.py b/test/perf/objselectspeed.py index 126c9c707..f64c73c69 100644 --- a/test/perf/objselectspeed.py +++ b/test/perf/objselectspeed.py @@ -38,14 +38,14 @@ def setup(): data = [{'name':'John Doe','sex':1,'age':35, 'type':'employee'}] * 100 for j in xrange(500): i.execute(data) - + # note we arent fetching from employee_table, # so we can leave it empty even though its "incorrect" #i = Employee_table.insert() #data = [{'foo':'foo', 'bar':'bar':'bat':'bat'}] * 100 #for j in xrange(500): # i.execute(data) - + print "Inserted 50,000 rows" def sqlite_select(entity_cls): diff --git a/test/perf/orm2010.py b/test/perf/orm2010.py index 46703b6da..d24376cc9 100644 --- a/test/perf/orm2010.py +++ b/test/perf/orm2010.py @@ -23,50 +23,50 @@ from sqlalchemy.ext.declarative import declarative_base import random import os from decimal import Decimal - + Base = declarative_base() class Employee(Base): __tablename__ = 'employee' - + id = Column(Integer, primary_key=True) name = Column(String(100), nullable=False) type = Column(String(50), nullable=False) - + __mapper_args__ = {'polymorphic_on':type} class Boss(Employee): __tablename__ = 'boss' - + id = Column(Integer, ForeignKey('employee.id'), primary_key=True) golf_average = Column(Numeric) - + __mapper_args__ = {'polymorphic_identity':'boss'} - + class Grunt(Employee): __tablename__ = 'grunt' - + id = Column(Integer, ForeignKey('employee.id'), primary_key=True) savings = Column(Numeric) - + employer_id = Column(Integer, ForeignKey('boss.id')) # Configure an 'employer' relationship, where Grunt references # Boss. This is a joined-table subclass to subclass relationship, # which is a less typical case. - + # In 0.7, "Boss.id" is the "id" column of "boss", as would be expected. if __version__ >= "0.7": employer = relationship("Boss", backref="employees", primaryjoin=Boss.id==employer_id) - - # Prior to 0.7, "Boss.id" is the "id" column of "employee". + + # Prior to 0.7, "Boss.id" is the "id" column of "employee". # Long story. So we hardwire the relationship against the "id" # column of Boss' table. elif __version__ >= "0.6": employer = relationship("Boss", backref="employees", primaryjoin=Boss.__table__.c.id==employer_id) - + # In 0.5, the many-to-one loader wouldn't recognize the above as a # simple "identity map" fetch. So to give 0.5 a chance to emit # the same amount of SQL as 0.6, we hardwire the relationship against @@ -75,9 +75,9 @@ class Grunt(Employee): employer = relationship("Boss", backref="employees", primaryjoin=Employee.__table__.c.id==employer_id, foreign_keys=employer_id) - + __mapper_args__ = {'polymorphic_identity':'grunt'} - + if os.path.exists('orm2010.db'): os.remove('orm2010.db') # use a file based database so that cursor.execute() has some @@ -99,9 +99,9 @@ def runit(): ] sess.add_all(bosses) - - - # create 10000 Grunt objects. + + + # create 10000 Grunt objects. grunts = [ Grunt( name="Grunt %d" % i, @@ -109,7 +109,7 @@ def runit(): ) for i in xrange(10000) ] - + # Assign each Grunt a Boss. Look them up in the DB # to simulate a little bit of two-way activity with the # DB while we populate. Autoflush occurs on each query. @@ -121,15 +121,15 @@ def runit(): first() for grunt in grunts[0:100]: grunt.employer = boss - + grunts = grunts[100:] sess.commit() report = [] - + # load all the Grunts, print a report with their name, stats, - # and their bosses' stats. + # and their bosses' stats. for grunt in sess.query(Grunt): # here, the overhead of a many-to-one fetch of # "grunt.employer" directly from the identity map @@ -160,7 +160,7 @@ print 'Total executemany calls: %d' \ "objects>", 0) os.system("runsnake %s" % filename) - + # SQLA Version: 0.7b1 # Total calls 4956750 # Total execute calls: 11201 @@ -178,9 +178,9 @@ os.system("runsnake %s" % filename) - - + + diff --git a/test/perf/sessions.py b/test/perf/sessions.py index 2fe4f758f..c1258e732 100644 --- a/test/perf/sessions.py +++ b/test/perf/sessions.py @@ -23,7 +23,7 @@ class SessionTest(TestBase, AssertsExecutionResults): Column('c2', String(30)), Column('t1id', Integer, ForeignKey('t1.c1')) ) - + metadata.create_all() l = [] @@ -35,7 +35,7 @@ class SessionTest(TestBase, AssertsExecutionResults): for y in range(1, 100): l.append({'c2':'this is t2 #%d' % y, 't1id':x}) t2.insert().execute(*l) - + class T1(_fixtures.Base): pass class T2(_fixtures.Base): @@ -45,12 +45,12 @@ class SessionTest(TestBase, AssertsExecutionResults): 't2s':relationship(T2, backref='t1') }) mapper(T2, t2) - + @classmethod def teardown_class(cls): metadata.drop_all() clear_mappers() - + @profiling.profiled('clean', report=True) def test_session_clean(self): for x in range(0, ITERATIONS): @@ -68,7 +68,7 @@ class SessionTest(TestBase, AssertsExecutionResults): for x in range(0, ITERATIONS): sess = create_session() t1s = sess.query(T1).filter(T1.c1.between(15, 48)).all() - + for index in [2, 7, 12, 15, 18, 20]: t1s[index].c2 = 'this is some modified text' for t2 in t1s[index].t2s: @@ -76,7 +76,7 @@ class SessionTest(TestBase, AssertsExecutionResults): del t1s gc_collect() - + sess.close() del sess gc_collect() diff --git a/test/sql/test_case_statement.py b/test/sql/test_case_statement.py index 7bc3ab31f..97220d4dd 100644 --- a/test/sql/test_case_statement.py +++ b/test/sql/test_case_statement.py @@ -94,31 +94,31 @@ class CaseTest(TestBase, AssertsCompiledSQL): def test_literal_interpretation(self): t = table('test', column('col1')) - + assert_raises(exc.ArgumentError, case, [("x", "y")]) - + self.assert_compile(case([("x", "y")], value=t.c.col1), "CASE test.col1 WHEN :param_1 THEN :param_2 END") self.assert_compile(case([(t.c.col1==7, "y")], else_="z"), "CASE WHEN (test.col1 = :col1_1) THEN :param_1 ELSE :param_2 END") - + def test_text_doesnt_explode(self): for s in [ select([case([(info_table.c.info == 'pk_4_data', text("'yes'"))], else_=text("'no'" ))]).order_by(info_table.c.info), - + select([case([(info_table.c.info == 'pk_4_data', literal_column("'yes'"))], else_=literal_column("'no'" ))]).order_by(info_table.c.info), - + ]: eq_(s.execute().fetchall(), [ (u'no', ), (u'no', ), (u'no', ), (u'yes', ), (u'no', ), (u'no', ), ]) - - - + + + @testing.fails_on('firebird', 'FIXME: unknown') @testing.fails_on('maxdb', 'FIXME: unknown') def testcase_with_dict(self): @@ -146,7 +146,7 @@ class CaseTest(TestBase, AssertsCompiledSQL): ], whereclause=info_table.c.pk < 4, from_obj=[info_table]) - + assert simple_query.execute().fetchall() == [ ('one', 1), ('two', 2), diff --git a/test/sql/test_compiler.py b/test/sql/test_compiler.py index b34eaeaae..d63e41e90 100644 --- a/test/sql/test_compiler.py +++ b/test/sql/test_compiler.py @@ -85,15 +85,15 @@ class SelectTest(TestBase, AssertsCompiledSQL): "SELECT mytable.myid, mytable.name, mytable.description, " "myothertable.otherid, myothertable.othername FROM mytable, " "myothertable") - + def test_invalid_col_argument(self): assert_raises(exc.ArgumentError, select, table1) assert_raises(exc.ArgumentError, select, table1.c.myid) - + def test_from_subquery(self): """tests placing select statements in the column clause of another select, for the purposes of selecting from the exported columns of that select.""" - + s = select([table1], table1.c.name == 'jack') self.assert_compile( select( @@ -163,7 +163,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): select([ClauseList(column('a'), column('b'))]).select_from('sometable'), 'SELECT a, b FROM sometable' ) - + def test_use_labels(self): self.assert_compile( select([table1.c.myid==5], use_labels=True), @@ -184,15 +184,15 @@ class SelectTest(TestBase, AssertsCompiledSQL): select([cast("data", Integer)], use_labels=True), "SELECT CAST(:param_1 AS INTEGER) AS anon_1" ) - + self.assert_compile( select([func.sum(func.lala(table1.c.myid).label('foo')).label('bar')]), "SELECT sum(lala(mytable.myid)) AS bar FROM mytable" ) - + def test_paramstyles(self): stmt = text("select :foo, :bar, :bat from sometable") - + self.assert_compile( stmt, "select ?, ?, ? from sometable" @@ -218,10 +218,10 @@ class SelectTest(TestBase, AssertsCompiledSQL): "select %(foo)s, %(bar)s, %(bat)s from sometable" , dialect=default.DefaultDialect(paramstyle='pyformat') ) - + def test_dupe_columns(self): """test that deduping is performed against clause element identity, not rendered result.""" - + self.assert_compile( select([column('a'), column('a'), column('a')]), "SELECT a, a, a" @@ -241,7 +241,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): "SELECT a, b" , dialect=default.DefaultDialect() ) - + self.assert_compile( select([bindparam('a'), bindparam('b'), bindparam('c')]), "SELECT :a, :b, :c" @@ -258,11 +258,11 @@ class SelectTest(TestBase, AssertsCompiledSQL): select(["a", "a", "a"]), "SELECT a, a, a" ) - + s = select([bindparam('a'), bindparam('b'), bindparam('c')]) s = s.compile(dialect=default.DefaultDialect(paramstyle='qmark')) eq_(s.positiontup, ['a', 'b', 'c']) - + def test_nested_uselabels(self): """test nested anonymous label generation. this essentially tests the ANONYMOUS_LABEL regex. @@ -285,7 +285,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): 'mytable.name AS name, mytable.description ' 'AS description FROM mytable) AS anon_2) ' 'AS anon_1') - + def test_dont_overcorrelate(self): self.assert_compile(select([table1], from_obj=[table1, table1.select()]), @@ -294,7 +294,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): "mytable.myid AS myid, mytable.name AS " "name, mytable.description AS description " "FROM mytable)") - + def test_full_correlate(self): # intentional t = table('t', column('a'), column('b')) @@ -302,7 +302,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): s2 = select([t.c.a, s]) self.assert_compile(s2, """SELECT t.a, (SELECT t.a WHERE t.a = :a_1) AS anon_1 FROM t""") - + # unintentional t2 = table('t2', column('c'), column('d')) s = select([t.c.a]).where(t.c.a==t2.c.d).as_scalar() @@ -313,18 +313,18 @@ class SelectTest(TestBase, AssertsCompiledSQL): s = s.correlate(t, t2) s2 =select([t, t2, s]) self.assert_compile(s, "SELECT t.a WHERE t.a = t2.d") - + def test_exists(self): s = select([table1.c.myid]).where(table1.c.myid==5) - + self.assert_compile(exists(s), "EXISTS (SELECT mytable.myid FROM mytable WHERE mytable.myid = :myid_1)" ) - + self.assert_compile(exists(s.as_scalar()), "EXISTS (SELECT mytable.myid FROM mytable WHERE mytable.myid = :myid_1)" ) - + self.assert_compile(exists([table1.c.myid], table1.c.myid == 5).select(), 'SELECT EXISTS (SELECT mytable.myid FROM ' @@ -375,7 +375,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): 'WHERE EXISTS (SELECT * FROM myothertable ' 'AS myothertable_1 WHERE ' 'myothertable_1.otherid = mytable.myid)') - + self.assert_compile( select([ or_( @@ -388,7 +388,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): "OR (EXISTS (SELECT * FROM myothertable WHERE " "myothertable.otherid = :otherid_2)) AS anon_1" ) - + def test_where_subquery(self): s = select([addresses.c.street], addresses.c.user_id @@ -619,7 +619,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): self.assert_compile( label('bar', column('foo', type_=String))+ 'foo', 'foo || :param_1') - + def test_conjunctions(self): a, b, c = 'a', 'b', 'c' @@ -630,7 +630,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): select([x.label('foo')]), 'SELECT a AND b AND c AS foo' ) - + self.assert_compile( and_(table1.c.myid == 12, table1.c.name=='asdf', table2.c.othername == 'foo', "sysdate() = today()"), @@ -651,7 +651,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): 'today()', checkparams = {'othername_1': 'asdf', 'othername_2':'foo', 'otherid_1': 9, 'myid_1': 12} ) - + def test_distinct(self): self.assert_compile( @@ -678,7 +678,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): select([func.count(distinct(table1.c.myid))]), "SELECT count(DISTINCT mytable.myid) AS count_1 FROM mytable" ) - + def test_operators(self): for (py_op, sql_op) in ((operator.add, '+'), (operator.mul, '*'), (operator.sub, '-'), @@ -730,7 +730,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): self.assert_(compiled == fwd_sql or compiled == rev_sql, "\n'" + compiled + "'\n does not match\n'" + fwd_sql + "'\n or\n'" + rev_sql + "'") - + for (py_op, op) in ( (operator.neg, '-'), (operator.inv, 'NOT '), @@ -739,11 +739,11 @@ class SelectTest(TestBase, AssertsCompiledSQL): (table1.c.myid, "mytable.myid"), (literal("foo"), ":param_1"), ): - + compiled = str(py_op(expr)) sql = "%s%s" % (op, sql) eq_(compiled, sql) - + self.assert_compile( table1.select((table1.c.myid != 12) & ~(table1.c.name=='john')), "SELECT mytable.myid, mytable.name, mytable.description FROM " @@ -837,7 +837,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): postgresql.PGDialect()), ]: self.assert_compile(expr, check, dialect=dialect) - + def test_match(self): for expr, check, dialect in [ (table1.c.myid.match('somstr'), @@ -853,7 +853,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): postgresql.dialect()), (table1.c.myid.match('somstr'), "CONTAINS (mytable.myid, :myid_1)", - oracle.dialect()), + oracle.dialect()), ]: self.assert_compile(expr, check, dialect=dialect) @@ -1160,7 +1160,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): "SELECT column1 AS foobar, column2 AS hoho, myid FROM " "(SELECT column1 AS foobar, column2 AS hoho, mytable.myid AS myid FROM mytable)" ) - + self.assert_compile( select(['col1','col2'], from_obj='tablename').alias('myalias'), "SELECT col1, col2 FROM tablename" @@ -1189,7 +1189,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): checkparams={'bar':4, 'whee': 7}, dialect=dialect ) - + # test escaping out text() params with a backslash self.assert_compile( text("select * from foo where clock='05:06:07' and mork='\:mindy'"), @@ -1243,23 +1243,23 @@ class SelectTest(TestBase, AssertsCompiledSQL): "SELECT CURRENT_DATE + s.a AS dates FROM generate_series(:x, :y, :z) as s(a)", checkparams={'y': None, 'x': None, 'z': None} ) - + self.assert_compile( s.params(x=5, y=6, z=7), "SELECT CURRENT_DATE + s.a AS dates FROM generate_series(:x, :y, :z) as s(a)", checkparams={'y': 6, 'x': 5, 'z': 7} ) - + @testing.emits_warning('.*empty sequence.*') def test_render_binds_as_literal(self): """test a compiler that renders binds inline into SQL in the columns clause.""" - + dialect = default.DefaultDialect() class Compiler(dialect.statement_compiler): ansi_bind_rules = True dialect.statement_compiler = Compiler - + self.assert_compile( select([literal("someliteral")]), "SELECT 'someliteral'", @@ -1283,23 +1283,23 @@ class SelectTest(TestBase, AssertsCompiledSQL): "SELECT mod(mytable.myid, 5) AS mod_1 FROM mytable", dialect=dialect ) - + self.assert_compile( select([literal("foo").in_([])]), "SELECT 'foo' != 'foo' AS anon_1", dialect=dialect ) - + assert_raises( exc.CompileError, bindparam("foo").in_([]).compile, dialect=dialect ) - - + + def test_literal(self): - + self.assert_compile(select([literal('foo')]), "SELECT :param_1") - + self.assert_compile(select([literal("foo") + literal("bar")], from_obj=[table1]), "SELECT :param_1 || :param_2 AS anon_1 FROM mytable") @@ -1334,7 +1334,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): expr, "SELECT mytable.name COLLATE latin1_german2_ci AS anon_1 FROM mytable") assert table1.c.name.collate('latin1_german2_ci').type is table1.c.name.type - + expr = select([table1.c.name.collate('latin1_german2_ci').label('k1')]).order_by('k1') self.assert_compile(expr,"SELECT mytable.name COLLATE latin1_german2_ci AS k1 FROM mytable ORDER BY k1") @@ -1384,8 +1384,8 @@ class SelectTest(TestBase, AssertsCompiledSQL): '''"table%name"."spaces % more spaces" AS "table%name_spaces % '''\ '''more spaces" FROM "table%name"''' ) - - + + def test_joins(self): self.assert_compile( join(table2, table1, table1.c.myid == table2.c.otherid).select(), @@ -1473,7 +1473,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): "select #1 has 2 columns, select #2 has 3", union, table3.select(), table1.select() ) - + x = union( select([table1], table1.c.myid == 5), select([table1], table1.c.myid == 12), @@ -1494,7 +1494,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): "FROM mytable UNION SELECT mytable.myid, mytable.name, " "mytable.description FROM mytable) UNION SELECT mytable.myid," " mytable.name, mytable.description FROM mytable") - + u1 = union( select([table1.c.myid, table1.c.name]), select([table2]), @@ -1507,7 +1507,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): "FROM thirdtable") assert u1.corresponding_column(table2.c.otherid) is u1.c.myid - + self.assert_compile( union( select([table1.c.myid, table1.c.name]), @@ -1557,7 +1557,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): "SELECT thirdtable.userid FROM thirdtable)" ) - + s = select([column('foo'), column('bar')]) # ORDER BY's even though not supported by all DB's, are rendered if requested @@ -1569,9 +1569,9 @@ class SelectTest(TestBase, AssertsCompiledSQL): union(s.order_by("foo").self_group(), s.order_by("bar").limit(10).self_group()), "(SELECT foo, bar ORDER BY foo) UNION (SELECT foo, bar ORDER BY bar LIMIT :param_1)", {'param_1':10} - + ) - + def test_compound_grouping(self): s = select([column('foo'), column('bar')]).select_from('bat') @@ -1580,19 +1580,19 @@ class SelectTest(TestBase, AssertsCompiledSQL): "((SELECT foo, bar FROM bat UNION SELECT foo, bar FROM bat) " "UNION SELECT foo, bar FROM bat) UNION SELECT foo, bar FROM bat" ) - + self.assert_compile( union(s, s, s, s), "SELECT foo, bar FROM bat UNION SELECT foo, bar " "FROM bat UNION SELECT foo, bar FROM bat UNION SELECT foo, bar FROM bat" ) - + self.assert_compile( union(s, union(s, union(s, s))), "SELECT foo, bar FROM bat UNION (SELECT foo, bar FROM bat " "UNION (SELECT foo, bar FROM bat UNION SELECT foo, bar FROM bat))" ) - + self.assert_compile( select([s.alias()]), 'SELECT anon_1.foo, anon_1.bar FROM (SELECT foo, bar FROM bat) AS anon_1' @@ -1654,8 +1654,8 @@ class SelectTest(TestBase, AssertsCompiledSQL): "UNION SELECT foo, bar FROM bat) " "UNION (SELECT foo, bar FROM bat " "UNION SELECT foo, bar FROM bat)") - - + + self.assert_compile( union( intersect(s, s), @@ -1817,9 +1817,9 @@ class SelectTest(TestBase, AssertsCompiledSQL): def test_binds_no_hash_collision(self): """test that construct_params doesn't corrupt dict due to hash collisions""" - + total_params = 100000 - + in_clause = [':in%d' % i for i in range(total_params)] params = dict(('in%d' % i, i) for i in range(total_params)) sql = 'text clause %s' % ', '.join(in_clause) @@ -1829,14 +1829,14 @@ class SelectTest(TestBase, AssertsCompiledSQL): pp = c.construct_params(params) eq_(len(set(pp)), total_params, '%s %s' % (len(set(pp)), len(pp))) eq_(len(set(pp.values())), total_params) - + def test_bind_as_col(self): t = table('foo', column('id')) s = select([t, literal('lala').label('hoho')]) self.assert_compile(s, "SELECT foo.id, :param_1 AS hoho FROM foo") - + assert [str(c) for c in s.c] == ["id", "hoho"] def test_bind_callable(self): @@ -1846,8 +1846,8 @@ class SelectTest(TestBase, AssertsCompiledSQL): "x = :key", {'x':12} ) - - + + @testing.emits_warning('.*empty sequence.*') def test_in(self): self.assert_compile(table1.c.myid.in_(['a']), @@ -1969,7 +1969,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): ), "(mytable.myid, mytable.name) IN ((myothertable.otherid, myothertable.othername))" ) - + self.assert_compile( tuple_(table1.c.myid, table1.c.name).in_( select([table2.c.otherid, table2.c.othername]) @@ -1977,8 +1977,8 @@ class SelectTest(TestBase, AssertsCompiledSQL): "(mytable.myid, mytable.name) IN (SELECT " "myothertable.otherid, myothertable.othername FROM myothertable)" ) - - + + def test_cast(self): tbl = table('casttest', column('id', Integer), @@ -2039,7 +2039,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): self.assert_compile(cast(literal_column('NULL'), Integer), 'CAST(NULL AS INTEGER)', dialect=sqlite.dialect()) - + def test_date_between(self): import datetime table = Table('dt', metadata, @@ -2085,15 +2085,15 @@ class SelectTest(TestBase, AssertsCompiledSQL): "SELECT op.field FROM op WHERE (op.field = op.field) BETWEEN :param_1 AND :param_2") self.assert_compile(table.select(between((table.c.field == table.c.field), False, True)), "SELECT op.field FROM op WHERE (op.field = op.field) BETWEEN :param_1 AND :param_2") - + def test_associativity(self): f = column('f') self.assert_compile( f - f, "f - f" ) self.assert_compile( f - f - f, "(f - f) - f" ) - + self.assert_compile( (f - f) - f, "(f - f) - f" ) self.assert_compile( (f - f).label('foo') - f, "(f - f) - f" ) - + self.assert_compile( f - (f - f), "f - (f - f)" ) self.assert_compile( f - (f - f).label('foo'), "f - (f - f)" ) @@ -2104,54 +2104,54 @@ class SelectTest(TestBase, AssertsCompiledSQL): self.assert_compile( f / f - f, "f / f - f" ) self.assert_compile( (f / f) - f, "f / f - f" ) self.assert_compile( (f / f).label('foo') - f, "f / f - f" ) - + # because / more precedent than - self.assert_compile( f - (f / f), "f - f / f" ) self.assert_compile( f - (f / f).label('foo'), "f - f / f" ) self.assert_compile( f - f / f, "f - f / f" ) self.assert_compile( (f - f) / f, "(f - f) / f" ) - + self.assert_compile( ((f - f) / f) - f, "(f - f) / f - f") self.assert_compile( (f - f) / (f - f), "(f - f) / (f - f)") - + # higher precedence self.assert_compile( (f / f) - (f / f), "f / f - f / f") self.assert_compile( (f / f) - (f - f), "f / f - (f - f)") self.assert_compile( (f / f) / (f - f), "(f / f) / (f - f)") self.assert_compile( f / (f / (f - f)), "f / (f / (f - f))") - - + + def test_delayed_col_naming(self): my_str = Column(String) - + sel1 = select([my_str]) - + assert_raises_message( exc.InvalidRequestError, "Cannot initialize a sub-selectable with this Column", lambda: sel1.c ) - + # calling label or as_scalar doesn't compile - # anything. + # anything. sel2 = select([func.substr(my_str, 2, 3)]).label('my_substr') - + assert_raises_message( exc.CompileError, "Cannot compile Column object until it's 'name' is assigned.", str, sel2 ) - + sel3 = select([my_str]).as_scalar() assert_raises_message( exc.CompileError, "Cannot compile Column object until it's 'name' is assigned.", str, sel3 ) - + my_str.name = 'foo' - + self.assert_compile( sel1, "SELECT foo", @@ -2160,18 +2160,18 @@ class SelectTest(TestBase, AssertsCompiledSQL): sel2, '(SELECT substr(foo, :substr_2, :substr_3) AS substr_1)', ) - + self.assert_compile( sel3, "(SELECT foo)" ) - + def test_naming(self): f1 = func.hoho(table1.c.name) s1 = select([table1.c.myid, table1.c.myid.label('foobar'), f1, func.lala(table1.c.name).label('gg')]) - + eq_( s1.c.keys(), ['myid', 'foobar', str(f1), 'gg'] @@ -2179,7 +2179,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): meta = MetaData() t1 = Table('mytable', meta, Column('col1', Integer)) - + exprs = ( table1.c.myid==12, func.hoho(table1.c.myid), @@ -2197,15 +2197,15 @@ class SelectTest(TestBase, AssertsCompiledSQL): t = col.table else: t = table1 - + s1 = select([col], from_obj=t) assert s1.c.keys() == [key], s1.c.keys() - + if label: self.assert_compile(s1, "SELECT %s AS %s FROM mytable" % (expr, label)) else: self.assert_compile(s1, "SELECT %s FROM mytable" % (expr,)) - + s1 = select([s1]) if label: self.assert_compile(s1, @@ -2220,7 +2220,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): self.assert_compile(s1, "SELECT %s FROM (SELECT %s FROM mytable)" % (expr,expr)) - + def test_hints(self): s = select([table1.c.myid]).with_hint(table1, "test hint %(name)s") @@ -2230,12 +2230,12 @@ class SelectTest(TestBase, AssertsCompiledSQL): a1 = table1.alias() s3 = select([a1.c.myid]).with_hint(a1, "index(%(name)s hint)") - + subs4 = select([ table1, table2 ]).select_from(table1.join(table2, table1.c.myid==table2.c.otherid)).\ with_hint(table1, 'hint1') - + s4 = select([table3]).select_from( table3.join( subs4, @@ -2243,7 +2243,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): ) ).\ with_hint(table3, 'hint3') - + subs5 = select([ table1, table2 ]).select_from(table1.join(table2, table1.c.myid==table2.c.otherid)) @@ -2255,12 +2255,12 @@ class SelectTest(TestBase, AssertsCompiledSQL): ).\ with_hint(table3, 'hint3').\ with_hint(table1, 'hint1') - + t1 = table('QuotedName', column('col1')) s6 = select([t1.c.col1]).where(t1.c.col1>10).with_hint(t1, '%(name)s idx1') a2 = t1.alias('SomeName') s7 = select([a2.c.col1]).where(a2.c.col1>10).with_hint(a2, '%(name)s idx1') - + mysql_d, oracle_d, sybase_d = \ mysql.dialect(), \ oracle.dialect(), \ @@ -2336,13 +2336,13 @@ class SelectTest(TestBase, AssertsCompiledSQL): and_("a", "b"), "a AND b" ) - + def test_literal_as_text_nonstring_raise(self): assert_raises(exc.ArgumentError, and_, ("a",), ("b",) ) - - + + class CRUDTest(TestBase, AssertsCompiledSQL): def test_insert(self): # generic insert, will create bind params for all columns @@ -2514,7 +2514,7 @@ class CRUDTest(TestBase, AssertsCompiledSQL): where(table1.c.name=='somename'), "DELETE FROM mytable WHERE mytable.myid = :myid_1 " "AND mytable.name = :name_1") - + def test_correlated_delete(self): # test a non-correlated WHERE clause s = select([table2.c.othername], table2.c.otherid == 7) @@ -2529,26 +2529,26 @@ class CRUDTest(TestBase, AssertsCompiledSQL): "DELETE FROM mytable WHERE mytable.name = (SELECT " "myothertable.othername FROM myothertable WHERE " "myothertable.otherid = mytable.myid)") - + def test_binds_that_match_columns(self): """test bind params named after column names replace the normal SET/VALUES generation.""" - + t = table('foo', column('x'), column('y')) u = t.update().where(t.c.x==bindparam('x')) - + assert_raises(exc.CompileError, u.compile) - + self.assert_compile(u, "UPDATE foo SET WHERE foo.x = :x", params={}) assert_raises(exc.CompileError, u.values(x=7).compile) - + self.assert_compile(u.values(y=7), "UPDATE foo SET y=:y WHERE foo.x = :x") - + assert_raises(exc.CompileError, u.values(x=7).compile, column_keys=['x', 'y']) assert_raises(exc.CompileError, u.compile, column_keys=['x', 'y']) - + self.assert_compile(u.values(x=3 + bindparam('x')), "UPDATE foo SET x=(:param_1 + :x) WHERE foo.x = :x") @@ -2574,7 +2574,7 @@ class CRUDTest(TestBase, AssertsCompiledSQL): i = t.insert().values(x=3 + bindparam('y'), y=5) assert_raises(exc.CompileError, i.compile) - + i = t.insert().values(x=3 + bindparam('x2')) self.assert_compile(i, "INSERT INTO foo (x) VALUES ((:param_1 + :x2))") self.assert_compile(i, "INSERT INTO foo (x) VALUES ((:param_1 + :x2))", params={}) @@ -2582,11 +2582,11 @@ class CRUDTest(TestBase, AssertsCompiledSQL): params={'x':1, 'y':2}) self.assert_compile(i, "INSERT INTO foo (x, y) VALUES ((:param_1 + :x2), :y)", params={'x2':1, 'y':2}) - + def test_labels_no_collision(self): - + t = table('foo', column('id'), column('foo_id')) - + self.assert_compile( t.update().where(t.c.id==5), "UPDATE foo SET id=:id, foo_id=:foo_id WHERE foo.id = :id_1" @@ -2596,7 +2596,7 @@ class CRUDTest(TestBase, AssertsCompiledSQL): t.update().where(t.c.id==bindparam(key=t.c.id._label)), "UPDATE foo SET id=:id, foo_id=:foo_id WHERE foo.id = :foo_id_1" ) - + class InlineDefaultTest(TestBase, AssertsCompiledSQL): def test_insert(self): m = MetaData() @@ -2634,7 +2634,7 @@ class SchemaTest(TestBase, AssertsCompiledSQL): self.assert_compile(table4.select(), "SELECT remote_owner.remotetable.rem_id, remote_owner.remotetable.datatype_id," " remote_owner.remotetable.value FROM remote_owner.remotetable") - + self.assert_compile(table4.select(and_(table4.c.datatype_id==7, table4.c.value=='hi')), "SELECT remote_owner.remotetable.rem_id, remote_owner.remotetable.datatype_id," " remote_owner.remotetable.value FROM remote_owner.remotetable WHERE " @@ -2664,7 +2664,7 @@ class SchemaTest(TestBase, AssertsCompiledSQL): ' "dbo.remote_owner".remotetable.value AS dbo_remote_owner_remotetable_value FROM' ' "dbo.remote_owner".remotetable' ) - + def test_alias(self): a = alias(table4, 'remtable') self.assert_compile(a.select(a.c.datatype_id==7), diff --git a/test/sql/test_constraints.py b/test/sql/test_constraints.py index 56c5c6205..fb07bf437 100644 --- a/test/sql/test_constraints.py +++ b/test/sql/test_constraints.py @@ -36,10 +36,10 @@ class ConstraintTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): def test_double_fk_usage_raises(self): f = ForeignKey('b.id') - + Column('x', Integer, f) assert_raises(exc.InvalidRequestError, Column, "y", Integer, f) - + def test_circular_constraint(self): a = Table("a", metadata, Column('id', Integer, primary_key=True), @@ -192,22 +192,22 @@ class ConstraintTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): ('sometable', 'this_name_is_too_long', 'ix_sometable_t_09aa'), ('sometable', 'this_name_alsois_long', 'ix_sometable_t_3cf1'), ]: - + t1 = Table(tname, MetaData(), Column(cname, Integer, index=True), ) ix1 = list(t1.indexes)[0] - + self.assert_compile( schema.CreateIndex(ix1), "CREATE INDEX %s " "ON %s (%s)" % (exp, tname, cname), dialect=dialect ) - + dialect.max_identifier_length = 22 dialect.max_index_name_length = None - + t1 = Table('t', MetaData(), Column('c', Integer)) assert_raises( exc.IdentifierError, @@ -217,7 +217,7 @@ class ConstraintTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): dialect=dialect ) - + class ConstraintCompilationTest(TestBase, AssertsCompiledSQL): def _test_deferrable(self, constraint_factory): @@ -225,11 +225,11 @@ class ConstraintCompilationTest(TestBase, AssertsCompiledSQL): Column('a', Integer), Column('b', Integer), constraint_factory(deferrable=True)) - + sql = str(schema.CreateTable(t).compile(bind=testing.db)) assert 'DEFERRABLE' in sql, sql assert 'NOT DEFERRABLE' not in sql, sql - + t = Table('tbl', MetaData(), Column('a', Integer), Column('b', Integer), @@ -291,18 +291,18 @@ class ConstraintCompilationTest(TestBase, AssertsCompiledSQL): CheckConstraint('a < b', deferrable=True, initially='DEFERRED'))) - + self.assert_compile( schema.CreateTable(t), "CREATE TABLE tbl (a INTEGER, b INTEGER CHECK (a < b) DEFERRABLE INITIALLY DEFERRED)" ) - + def test_use_alter(self): m = MetaData() t = Table('t', m, Column('a', Integer), ) - + t2 = Table('t2', m, Column('a', Integer, ForeignKey('t.a', use_alter=True, name='fk_ta')), Column('b', Integer, ForeignKey('t.a', name='fk_tb')), # to ensure create ordering ... @@ -320,25 +320,25 @@ class ConstraintCompilationTest(TestBase, AssertsCompiledSQL): 'DROP TABLE t2', 'DROP TABLE t' ]) - - + + def test_add_drop_constraint(self): m = MetaData() - + t = Table('tbl', m, Column('a', Integer), Column('b', Integer) ) - + t2 = Table('t2', m, Column('a', Integer), Column('b', Integer) ) - + constraint = CheckConstraint('a < b',name="my_test_constraint", deferrable=True,initially='DEFERRED', table=t) - + # before we create an AddConstraint, # the CONSTRAINT comes out inline self.assert_compile( @@ -397,13 +397,13 @@ class ConstraintCompilationTest(TestBase, AssertsCompiledSQL): schema.AddConstraint(constraint), "ALTER TABLE t2 ADD CONSTRAINT uq_cst UNIQUE (a, b)" ) - + constraint = UniqueConstraint(t2.c.a, t2.c.b, name="uq_cs2") self.assert_compile( schema.AddConstraint(constraint), "ALTER TABLE t2 ADD CONSTRAINT uq_cs2 UNIQUE (a, b)" ) - + assert t.c.a.primary_key is False constraint = PrimaryKeyConstraint(t.c.a) assert t.c.a.primary_key is True @@ -411,5 +411,5 @@ class ConstraintCompilationTest(TestBase, AssertsCompiledSQL): schema.AddConstraint(constraint), "ALTER TABLE tbl ADD PRIMARY KEY (a)" ) - - + + diff --git a/test/sql/test_defaults.py b/test/sql/test_defaults.py index 7ec43f8d2..31759a709 100644 --- a/test/sql/test_defaults.py +++ b/test/sql/test_defaults.py @@ -147,7 +147,7 @@ class DefaultTest(testing.TestBase): assert_raises_message(sa.exc.ArgumentError, ex_msg, sa.ColumnDefault, fn) - + def test_arg_signature(self): def fn1(): pass def fn2(): pass @@ -277,7 +277,7 @@ class DefaultTest(testing.TestBase): assert r.lastrow_has_defaults() eq_(set(r.context.postfetch_cols), set([t.c.col3, t.c.col5, t.c.col4, t.c.col6])) - + eq_(t.select(t.c.col1==54).execute().fetchall(), [(54, 'imthedefault', f, ts, ts, ctexec, True, False, 12, today, None)]) @@ -301,7 +301,7 @@ class DefaultTest(testing.TestBase): 12, today, 'py'), (53, 'imthedefault', f, ts, ts, ctexec, True, False, 12, today, 'py')]) - + def test_missing_many_param(self): assert_raises_message(exc.InvalidRequestError, "A value is required for bind parameter 'col7', in parameter group 1", @@ -310,7 +310,7 @@ class DefaultTest(testing.TestBase): {'col4':7, 'col8':19}, {'col4':7, 'col7':12, 'col8':19}, ) - + def test_insert_values(self): t.insert(values={'col3':50}).execute() l = t.select().execute() @@ -366,7 +366,7 @@ class DefaultTest(testing.TestBase): l = l.first() eq_(55, l['col3']) - + class PKDefaultTest(_base.TablesTest): __requires__ = ('subqueries',) @@ -379,14 +379,14 @@ class PKDefaultTest(_base.TablesTest): Column('id', Integer, primary_key=True, default=sa.select([func.max(t2.c.nextid)]).as_scalar()), Column('data', String(30))) - + @testing.requires.returning def test_with_implicit_returning(self): self._test(True) - + def test_regular(self): self._test(False) - + @testing.resolve_artifact_names def _test(self, returning): if not returning and not testing.db.dialect.implicit_returning: @@ -442,7 +442,7 @@ class PKIncrementTest(_base.TablesTest): ids.add(last) eq_(ids, set([1,2,3,4])) - + eq_(list(bind.execute(aitable.select().order_by(aitable.c.id))), [(1, 1, None), (2, None, 'row 2'), (3, 3, 'row 3'), (4, 4, None)]) @@ -477,7 +477,7 @@ class EmptyInsertTest(testing.TestBase): t1 = Table('t1', metadata, Column('is_true', Boolean, server_default=('1'))) metadata.create_all() - + try: result = t1.insert().execute() eq_(1, select([func.count(text('*'))], from_obj=t1).scalar()) @@ -588,7 +588,7 @@ class SequenceTest(testing.TestBase, testing.AssertsCompiledSQL): "DROP SEQUENCE foo_seq", use_default_dialect=True, ) - + @testing.fails_on('firebird', 'no FB support for start/increment') @testing.requires.sequences @@ -605,10 +605,10 @@ class SequenceTest(testing.TestBase, testing.AssertsCompiledSQL): start = seq.start or 1 inc = seq.increment or 1 assert values == list(xrange(start, start + inc * 3, inc)) - + finally: seq.drop(testing.db) - + @testing.requires.sequences def test_seq_nonpk(self): """test sequences fire off as defaults on non-pk columns""" diff --git a/test/sql/test_functions.py b/test/sql/test_functions.py index 0fb2ca5f7..13116a4bb 100644 --- a/test/sql/test_functions.py +++ b/test/sql/test_functions.py @@ -26,8 +26,8 @@ class CompileTest(TestBase, AssertsCompiledSQL): self.assert_compile(func.nosuchfunction(), "nosuchfunction", dialect=dialect) else: self.assert_compile(func.nosuchfunction(), "nosuchfunction()", dialect=dialect) - - # test generic function compile + + # test generic function compile class fake_func(GenericFunction): __return_type__ = sqltypes.Integer @@ -39,14 +39,14 @@ class CompileTest(TestBase, AssertsCompiledSQL): "fake_func(%s)" % bindtemplate % {'name':'param_1', 'position':1}, dialect=dialect) - + def test_use_labels(self): self.assert_compile(select([func.foo()], use_labels=True), "SELECT foo() AS foo_1" ) def test_underscores(self): self.assert_compile(func.if_(), "if()") - + def test_generic_now(self): assert isinstance(func.now().type, sqltypes.DateTime) @@ -69,10 +69,10 @@ class CompileTest(TestBase, AssertsCompiledSQL): ('random', oracle.dialect()) ]: self.assert_compile(func.random(), ret, dialect=dialect) - + def test_namespacing_conflicts(self): self.assert_compile(func.text('foo'), 'text(:text_1)') - + def test_generic_count(self): assert isinstance(func.count().type, sqltypes.Integer) @@ -101,7 +101,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): assert True def test_return_type_detection(self): - + for fn in [func.coalesce, func.max, func.min, func.sum]: for args, type_ in [ ((datetime.date(2007, 10, 5), @@ -113,7 +113,7 @@ class CompileTest(TestBase, AssertsCompiledSQL): datetime.datetime(2005, 10, 15, 14, 45, 33)), sqltypes.DateTime) ]: assert isinstance(fn(*args).type, type_), "%s / %s" % (fn(), type_) - + assert isinstance(func.concat("foo", "bar").type, sqltypes.String) @@ -193,7 +193,7 @@ class ExecuteTest(TestBase): @engines.close_first def tearDown(self): pass - + def test_standalone_execute(self): x = testing.db.func.current_date().execute().scalar() y = testing.db.func.current_date().select().execute().scalar() @@ -208,10 +208,10 @@ class ExecuteTest(TestBase): def test_conn_execute(self): from sqlalchemy.sql.expression import FunctionElement from sqlalchemy.ext.compiler import compiles - + class myfunc(FunctionElement): type = Date() - + @compiles(myfunc) def compile(elem, compiler, **kw): return compiler.process(func.current_date()) @@ -229,17 +229,17 @@ class ExecuteTest(TestBase): def test_exec_options(self): f = func.foo() eq_(f._execution_options, {}) - + f = f.execution_options(foo='bar') eq_(f._execution_options, {'foo':'bar'}) s = f.select() eq_(s._execution_options, {'foo':'bar'}) - + ret = testing.db.execute(func.now().execution_options(foo='bar')) eq_(ret.context.execution_options, {'foo':'bar'}) ret.close() - - + + @engines.close_first def test_update(self): """ diff --git a/test/sql/test_generative.py b/test/sql/test_generative.py index e129f69c4..627736370 100644 --- a/test/sql/test_generative.py +++ b/test/sql/test_generative.py @@ -27,7 +27,7 @@ class TraversalTest(TestBase, AssertsExecutionResults): return other is self __hash__ = ClauseElement.__hash__ - + def __eq__(self, other): return other.expr == self.expr @@ -100,7 +100,7 @@ class TraversalTest(TestBase, AssertsExecutionResults): s2 = vis.traverse(struct) assert struct == s2 assert not struct.is_other(s2) - + def test_no_clone(self): struct = B(A("expr1"), A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3")) @@ -151,9 +151,9 @@ class TraversalTest(TestBase, AssertsExecutionResults): class CustomObj(Column): pass - + assert CustomObj.__visit_name__ == Column.__visit_name__ == 'column' - + foo, bar = CustomObj('foo', String), CustomObj('bar', String) bin = foo == bar s = set(ClauseVisitor().iterate(bin)) @@ -193,7 +193,7 @@ class ClauseTest(TestBase, AssertsCompiledSQL): f = sql_util.ClauseAdapter(a).traverse(f) self.assert_compile(select([f]), "SELECT t1_1.col1 * :col1_1 AS anon_1 FROM t1 AS t1_1") - + def test_join(self): clause = t1.join(t2, t1.c.col2==t2.c.col2) c1 = str(clause) @@ -206,20 +206,20 @@ class ClauseTest(TestBase, AssertsCompiledSQL): clause2 = Vis().traverse(clause) assert c1 == str(clause) assert str(clause2) == str(t1.join(t2, t1.c.col2==t2.c.col3)) - + def test_aliased_column_adapt(self): clause = t1.select() - + aliased = t1.select().alias() aliased2 = t1.alias() adapter = sql_util.ColumnAdapter(aliased) - + f = select([ adapter.columns[c] for c in aliased2.c ]).select_from(aliased) - + s = select([aliased2]).select_from(aliased) eq_(str(s), str(f)) @@ -230,8 +230,8 @@ class ClauseTest(TestBase, AssertsCompiledSQL): str(select([func.count(aliased2.c.col1)]).select_from(aliased)), str(f) ) - - + + def test_text(self): clause = text("select * from table where foo=:bar", bindparams=[bindparam('bar')]) c1 = str(clause) @@ -288,7 +288,7 @@ class ClauseTest(TestBase, AssertsCompiledSQL): print str(s5) assert str(s5) == s5_assert assert str(s4) == s4_assert - + def test_union(self): u = union(t1.select(), t2.select()) u2 = CloningVisitor().traverse(u) @@ -300,27 +300,27 @@ class ClauseTest(TestBase, AssertsCompiledSQL): u2 = CloningVisitor().traverse(u) assert str(u) == str(u2) assert [str(c) for c in u2.c] == cols - + s1 = select([t1], t1.c.col1 == bindparam('id_param')) s2 = select([t2]) u = union(s1, s2) - + u2 = u.params(id_param=7) u3 = u.params(id_param=10) assert str(u) == str(u2) == str(u3) assert u2.compile().params == {'id_param':7} assert u3.compile().params == {'id_param':10} - + def test_in(self): expr = t1.c.col1.in_(['foo', 'bar']) expr2 = CloningVisitor().traverse(expr) assert str(expr) == str(expr2) - + def test_adapt_union(self): u = union(t1.select().where(t1.c.col1==4), t1.select().where(t1.c.col1==5)).alias() - + assert sql_util.ClauseAdapter(u).traverse(t1) is u - + def test_binds(self): """test that unique bindparams change their name upon clone() to prevent conflicts""" @@ -340,17 +340,17 @@ class ClauseTest(TestBase, AssertsCompiledSQL): "table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) AS anon_1, "\ "(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_2) AS anon_2 "\ "WHERE anon_1.col2 = anon_2.col2") - + def test_extract(self): s = select([extract('foo', t1.c.col1).label('col1')]) self.assert_compile(s, "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1") - + s2 = CloningVisitor().traverse(s).alias() s3 = select([s2.c.col1]) self.assert_compile(s, "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1") self.assert_compile(s3, "SELECT anon_1.col1 FROM (SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1) AS anon_1") - - + + @testing.emits_warning('.*replaced by another column with the same key') def test_alias(self): subq = t2.select().alias('subq') @@ -372,7 +372,7 @@ class ClauseTest(TestBase, AssertsCompiledSQL): s = select([t1.c.col1, subq.c.col1], from_obj=[t1, subq, t1.join(subq, t1.c.col1==subq.c.col2)]) s5 = CloningVisitor().traverse(s) assert orig == str(s) == str(s5) - + def test_correlated_select(self): s = select(['*'], t1.c.col1==t2.c.col1, from_obj=[t1, t2]).correlate(t2) class Vis(CloningVisitor): @@ -380,32 +380,32 @@ class ClauseTest(TestBase, AssertsCompiledSQL): select.append_whereclause(t1.c.col2==7) self.assert_compile(Vis().traverse(s), "SELECT * FROM table1 WHERE table1.col1 = table2.col1 AND table1.col2 = :col2_1") - + def test_this_thing(self): s = select([t1]).where(t1.c.col1=='foo').alias() s2 = select([s.c.col1]) - + self.assert_compile(s2, "SELECT anon_1.col1 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) AS anon_1") t1a = t1.alias() s2 = sql_util.ClauseAdapter(t1a).traverse(s2) self.assert_compile(s2, "SELECT anon_1.col1 FROM (SELECT table1_1.col1 AS col1, table1_1.col2 AS col2, table1_1.col3 AS col3 FROM table1 AS table1_1 WHERE table1_1.col1 = :col1_1) AS anon_1") - + def test_select_fromtwice(self): t1a = t1.alias() - + s = select([1], t1.c.col1==t1a.c.col1, from_obj=t1a).correlate(t1) self.assert_compile(s, "SELECT 1 FROM table1 AS table1_1 WHERE table1.col1 = table1_1.col1") - + s = CloningVisitor().traverse(s) self.assert_compile(s, "SELECT 1 FROM table1 AS table1_1 WHERE table1.col1 = table1_1.col1") - + s = select([t1]).where(t1.c.col1=='foo').alias() - + s2 = select([1], t1.c.col1==s.c.col1, from_obj=s).correlate(t1) self.assert_compile(s2, "SELECT 1 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) AS anon_1 WHERE table1.col1 = anon_1.col1") s2 = ReplacingCloningVisitor().traverse(s2) self.assert_compile(s2, "SELECT 1 FROM (SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) AS anon_1 WHERE table1.col1 = anon_1.col1") - + class ClauseAdapterTest(TestBase, AssertsCompiledSQL): @classmethod def setup_class(cls): @@ -446,7 +446,7 @@ class ClauseAdapterTest(TestBase, AssertsCompiledSQL): self.assert_compile(select(['*'], t2alias.c.col1==s), "SELECT * FROM table2 AS t2alias WHERE t2alias.col1 = (SELECT * FROM table1 AS t1alias)") s = CloningVisitor().traverse(s) self.assert_compile(select(['*'], t2alias.c.col1==s), "SELECT * FROM table2 AS t2alias WHERE t2alias.col1 = (SELECT * FROM table1 AS t1alias)") - + s = select(['*']).where(t1.c.col1==t2.c.col1).as_scalar() self.assert_compile(select([t1.c.col1, s]), "SELECT table1.col1, (SELECT * FROM table2 WHERE table1.col1 = table2.col1) AS anon_1 FROM table1") vis = sql_util.ClauseAdapter(t1alias) @@ -478,7 +478,7 @@ class ClauseAdapterTest(TestBase, AssertsCompiledSQL): j1 = addresses.join(ualias, addresses.c.user_id==ualias.c.id) self.assert_compile(sql_util.ClauseAdapter(j1).traverse(s), "SELECT count(addresses.id) AS count_1 FROM addresses WHERE users_1.id = addresses.user_id") - + def test_table_to_alias(self): t1alias = t1.alias('t1alias') @@ -543,7 +543,7 @@ class ClauseAdapterTest(TestBase, AssertsCompiledSQL): a = Table('a', m, Column('x', Integer), Column('y', Integer)) b = Table('b', m, Column('x', Integer), Column('y', Integer)) c = Table('c', m, Column('x', Integer), Column('y', Integer)) - + # force a recursion overflow, by linking a.c.x<->c.c.x, and # asking for a nonexistent col. corresponding_column should prevent # endless depth. @@ -557,13 +557,13 @@ class ClauseAdapterTest(TestBase, AssertsCompiledSQL): c = Table('c', m, Column('x', Integer), Column('y', Integer)) alias = select([a]).select_from(a.join(b, a.c.x==b.c.x)).alias() - + # two levels of indirection from c.x->b.x->a.x, requires recursive # corresponding_column call adapt = sql_util.ClauseAdapter(alias, equivalents= {b.c.x: set([ a.c.x]), c.c.x:set([b.c.x])}) assert adapt._corresponding_column(a.c.x, False) is alias.c.x assert adapt._corresponding_column(c.c.x, False) is alias.c.x - + def test_join_to_alias(self): metadata = MetaData() a = Table('a', metadata, @@ -642,13 +642,13 @@ class ClauseAdapterTest(TestBase, AssertsCompiledSQL): "(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1) AS foo LIMIT :param_1 OFFSET :param_2) AS anon_1 "\ "LEFT OUTER JOIN table1 AS bar ON anon_1.col1 = bar.col1", {'param_1':5, 'param_2':10}) - + def test_functions(self): self.assert_compile(sql_util.ClauseAdapter(t1.alias()).traverse(func.count(t1.c.col1)), "count(table1_1.col1)") s = select([func.count(t1.c.col1)]) self.assert_compile(sql_util.ClauseAdapter(t1.alias()).traverse(s), "SELECT count(table1_1.col1) AS count_1 FROM table1 AS table1_1") - + def test_recursive(self): metadata = MetaData() a = Table('a', metadata, @@ -670,8 +670,8 @@ class ClauseAdapterTest(TestBase, AssertsCompiledSQL): u = union( a.join(b).select().apply_labels(), a.join(d).select().apply_labels() - ).alias() - + ).alias() + self.assert_compile( sql_util.ClauseAdapter(u).traverse(select([c.c.bid]).where(c.c.bid==u.c.b_aid)), "SELECT c.bid "\ @@ -687,16 +687,16 @@ class SpliceJoinsTest(TestBase, AssertsCompiledSQL): global table1, table2, table3, table4 def _table(name): return table(name, column("col1"), column("col2"),column("col3")) - - table1, table2, table3, table4 = [_table(name) for name in ("table1", "table2", "table3", "table4")] + + table1, table2, table3, table4 = [_table(name) for name in ("table1", "table2", "table3", "table4")] def test_splice(self): (t1, t2, t3, t4) = (table1, table2, table1.alias(), table2.alias()) - + j = t1.join(t2, t1.c.col1==t2.c.col1).join(t3, t2.c.col1==t3.c.col1).join(t4, t4.c.col1==t1.c.col1) - + s = select([t1]).where(t1.c.col2<5).alias() - + self.assert_compile(sql_util.splice_joins(s, j), "(SELECT table1.col1 AS col1, table1.col2 AS col2, "\ "table1.col3 AS col3 FROM table1 WHERE table1.col2 < :col2_1) AS anon_1 "\ @@ -705,12 +705,12 @@ class SpliceJoinsTest(TestBase, AssertsCompiledSQL): def test_stop_on(self): (t1, t2, t3) = (table1, table2, table3) - + j1= t1.join(t2, t1.c.col1==t2.c.col1) j2 = j1.join(t3, t2.c.col1==t3.c.col1) - + s = select([t1]).select_from(j1).alias() - + self.assert_compile(sql_util.splice_joins(s, j2), "(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 JOIN table2 "\ "ON table1.col1 = table2.col1) AS anon_1 JOIN table2 ON anon_1.col1 = table2.col1 JOIN table3 "\ @@ -720,27 +720,27 @@ class SpliceJoinsTest(TestBase, AssertsCompiledSQL): self.assert_compile(sql_util.splice_joins(s, j2, j1), "(SELECT table1.col1 AS col1, table1.col2 AS col2, table1.col3 AS col3 FROM table1 "\ "JOIN table2 ON table1.col1 = table2.col1) AS anon_1 JOIN table3 ON table2.col1 = table3.col1") - + def test_splice_2(self): t2a = table2.alias() t3a = table3.alias() j1 = table1.join(t2a, table1.c.col1==t2a.c.col1).join(t3a, t2a.c.col2==t3a.c.col2) - + t2b = table4.alias() j2 = table1.join(t2b, table1.c.col3==t2b.c.col3) - + self.assert_compile(sql_util.splice_joins(table1, j1), "table1 JOIN table2 AS table2_1 ON table1.col1 = table2_1.col1 "\ "JOIN table3 AS table3_1 ON table2_1.col2 = table3_1.col2") - + self.assert_compile(sql_util.splice_joins(table1, j2), "table1 JOIN table4 AS table4_1 ON table1.col3 = table4_1.col3") self.assert_compile(sql_util.splice_joins(sql_util.splice_joins(table1, j1), j2), "table1 JOIN table2 AS table2_1 ON table1.col1 = table2_1.col1 "\ "JOIN table3 AS table3_1 ON table2_1.col2 = table3_1.col2 "\ "JOIN table4 AS table4_1 ON table1.col3 = table4_1.col3") - - + + class SelectTest(TestBase, AssertsCompiledSQL): """tests the generative capability of Select""" @@ -838,7 +838,7 @@ class SelectTest(TestBase, AssertsCompiledSQL): assert s._execution_options == dict(foo='bar') # s2 should have its execution_options based on s, though. assert s2._execution_options == dict(foo='bar', bar='baz') - + # this feature not available yet def _NOTYET_test_execution_options_in_text(self): s = text('select 42', execution_options=dict(foo='bar')) diff --git a/test/sql/test_labels.py b/test/sql/test_labels.py index 0f84c30a0..9160aa3ee 100644 --- a/test/sql/test_labels.py +++ b/test/sql/test_labels.py @@ -51,7 +51,7 @@ class LongLabelsTest(TestBase, AssertsCompiledSQL): assert_raises(exceptions.IdentifierError, m.drop_all) assert_raises(exceptions.IdentifierError, t1.create) assert_raises(exceptions.IdentifierError, t1.drop) - + def test_result(self): table1.insert().execute(**{"this_is_the_primarykey_column":1, "this_is_the_data_column":"data1"}) table1.insert().execute(**{"this_is_the_primarykey_column":2, "this_is_the_data_column":"data2"}) @@ -82,7 +82,7 @@ class LongLabelsTest(TestBase, AssertsCompiledSQL): (1, "data1"), (2, "data2"), ], repr(result) - + @testing.requires.offset def go(): r = s.limit(2).offset(1).execute() @@ -94,7 +94,7 @@ class LongLabelsTest(TestBase, AssertsCompiledSQL): (3, "data3"), ], repr(result) go() - + def test_table_alias_names(self): if testing.against('oracle'): self.assert_compile( @@ -113,7 +113,7 @@ class LongLabelsTest(TestBase, AssertsCompiledSQL): self.assert_compile( select([table1, ta]).select_from(table1.join(ta, table1.c.this_is_the_data_column==ta.c.this_is_the_data_column)).\ where(ta.c.this_is_the_data_column=='data3'), - + "SELECT some_large_named_table.this_is_the_primarykey_column, some_large_named_table.this_is_the_data_column, " "table_with_exactly_29_c_1.this_is_the_primarykey_column, table_with_exactly_29_c_1.this_is_the_data_column FROM " "some_large_named_table JOIN table_with_exactly_29_characs AS table_with_exactly_29_c_1 ON " @@ -121,17 +121,17 @@ class LongLabelsTest(TestBase, AssertsCompiledSQL): "WHERE table_with_exactly_29_c_1.this_is_the_data_column = :this_is_the_data_column_1", dialect=dialect ) - + table2.insert().execute( {"this_is_the_primarykey_column":1, "this_is_the_data_column":"data1"}, {"this_is_the_primarykey_column":2, "this_is_the_data_column":"data2"}, {"this_is_the_primarykey_column":3, "this_is_the_data_column":"data3"}, {"this_is_the_primarykey_column":4, "this_is_the_data_column":"data4"}, ) - + r = table2.alias().select().execute() assert r.fetchall() == [(x, "data%d" % x) for x in range(1, 5)] - + def test_colbinds(self): table1.insert().execute(**{"this_is_the_primarykey_column":1, "this_is_the_data_column":"data1"}) table1.insert().execute(**{"this_is_the_primarykey_column":2, "this_is_the_data_column":"data2"}) @@ -201,5 +201,5 @@ class LongLabelsTest(TestBase, AssertsCompiledSQL): self.assert_compile(x, "SELECT _1.this_is_the_primarykey_column AS _1, _1.this_is_the_data_column AS _2 FROM " "(SELECT some_large_named_table.this_is_the_primarykey_column AS _3, some_large_named_table.this_is_the_data_column AS _4 " "FROM some_large_named_table WHERE some_large_named_table.this_is_the_primarykey_column = :_1) AS _1", dialect=compile_dialect) - - + + diff --git a/test/sql/test_metadata.py b/test/sql/test_metadata.py index c5ef48154..75eac9ee8 100644 --- a/test/sql/test_metadata.py +++ b/test/sql/test_metadata.py @@ -32,7 +32,7 @@ class MetaDataTest(TestBase, ComparesTables): t2 = Table('t2', metadata, Column('x', Integer), schema='foo') t3 = Table('t2', MetaData(), Column('x', Integer)) t4 = Table('t1', MetaData(), Column('x', Integer), schema='foo') - + assert "t1" in metadata assert "foo.t2" in metadata assert "t2" not in metadata @@ -41,7 +41,7 @@ class MetaDataTest(TestBase, ComparesTables): assert t2 in metadata assert t3 not in metadata assert t4 not in metadata - + def test_uninitialized_column_copy(self): for col in [ Column('foo', String(), nullable=False), @@ -76,24 +76,24 @@ class MetaDataTest(TestBase, ComparesTables): cx = c1.copy() t = Table('foo%d' % i, m, cx) eq_(msgs, ['attach foo0.foo', 'attach foo1.foo', 'attach foo2.foo']) - + def test_schema_collection_add(self): metadata = MetaData() - + t1 = Table('t1', metadata, Column('x', Integer), schema='foo') t2 = Table('t2', metadata, Column('x', Integer), schema='bar') t3 = Table('t3', metadata, Column('x', Integer)) - + eq_(metadata._schemas, set(['foo', 'bar'])) eq_(len(metadata.tables), 3) - + def test_schema_collection_remove(self): metadata = MetaData() - + t1 = Table('t1', metadata, Column('x', Integer), schema='foo') t2 = Table('t2', metadata, Column('x', Integer), schema='bar') t3 = Table('t3', metadata, Column('x', Integer), schema='bar') - + metadata.remove(t3) eq_(metadata._schemas, set(['foo', 'bar'])) eq_(len(metadata.tables), 2) @@ -101,28 +101,28 @@ class MetaDataTest(TestBase, ComparesTables): metadata.remove(t1) eq_(metadata._schemas, set(['bar'])) eq_(len(metadata.tables), 1) - + def test_schema_collection_remove_all(self): metadata = MetaData() - + t1 = Table('t1', metadata, Column('x', Integer), schema='foo') t2 = Table('t2', metadata, Column('x', Integer), schema='bar') metadata.clear() eq_(metadata._schemas, set()) eq_(len(metadata.tables), 0) - + def test_metadata_tables_immutable(self): metadata = MetaData() - + t1 = Table('t1', metadata, Column('x', Integer)) assert 't1' in metadata.tables - + assert_raises( TypeError, lambda: metadata.tables.pop('t1') ) - + @testing.provide_metadata def test_dupe_tables(self): t1 = Table('table1', metadata, @@ -143,28 +143,28 @@ class MetaDataTest(TestBase, ComparesTables): "Table object.", go ) - + def test_fk_copy(self): c1 = Column('foo', Integer) c2 = Column('bar', Integer) m = MetaData() t1 = Table('t', m, c1, c2) - + kw = dict(onupdate="X", ondelete="Y", use_alter=True, name='f1', deferrable="Z", initially="Q", link_to_name=True) - + fk1 = ForeignKey(c1, **kw) fk2 = ForeignKeyConstraint((c1,), (c2,), **kw) - + t1.append_constraint(fk2) fk1c = fk1.copy() fk2c = fk2.copy() - + for k in kw: eq_(getattr(fk1c, k), kw[k]) eq_(getattr(fk2c, k), kw[k]) - + def test_fk_construct(self): c1 = Column('foo', Integer) c2 = Column('bar', Integer) @@ -172,7 +172,7 @@ class MetaDataTest(TestBase, ComparesTables): t1 = Table('t', m, c1, c2) fk1 = ForeignKeyConstraint(('foo', ), ('bar', ), table=t1) assert fk1 in t1.constraints - + @testing.exclude('mysql', '<', (4, 1, 1), 'early types are squirrely') def test_to_metadata(self): meta = MetaData() @@ -264,7 +264,7 @@ class MetaDataTest(TestBase, ComparesTables): assert not c.columns.contains_column(table.c.name) finally: meta.drop_all(testing.db) - + def test_tometadata_with_schema(self): meta = MetaData() @@ -314,7 +314,7 @@ class MetaDataTest(TestBase, ComparesTables): Column('data2', Integer), ) Index('multi',table.c.data1,table.c.data2), - + meta2 = MetaData() table_c = table.tometadata(meta2) @@ -322,7 +322,7 @@ class MetaDataTest(TestBase, ComparesTables): return [i.name,i.unique] + \ sorted(i.kwargs.items()) + \ i.columns.keys() - + eq_( sorted([_get_key(i) for i in table.indexes]), sorted([_get_key(i) for i in table_c.indexes]) @@ -330,7 +330,7 @@ class MetaDataTest(TestBase, ComparesTables): @emits_warning("Table '.+' already exists within the given MetaData") def test_tometadata_already_there(self): - + meta1 = MetaData() table1 = Table('mytable', meta1, Column('myid', Integer, primary_key=True), @@ -341,7 +341,7 @@ class MetaDataTest(TestBase, ComparesTables): ) meta3 = MetaData() - + table_c = table1.tometadata(meta2) table_d = table2.tometadata(meta2) @@ -384,7 +384,7 @@ class MetaDataTest(TestBase, ComparesTables): c = Table('c', meta, Column('foo', Integer)) d = Table('d', meta, Column('foo', Integer)) e = Table('e', meta, Column('foo', Integer)) - + e.add_is_dependent_on(c) a.add_is_dependent_on(b) b.add_is_dependent_on(d) @@ -394,7 +394,7 @@ class MetaDataTest(TestBase, ComparesTables): meta.sorted_tables, [d, b, a, c, e] ) - + def test_tometadata_strip_schema(self): meta = MetaData() @@ -433,7 +433,7 @@ class TableTest(TestBase, AssertsCompiledSQL): table1 = Table("temporary_table_1", MetaData(), Column("col1", Integer), prefixes = ["TEMPORARY"]) - + self.assert_compile( schema.CreateTable(table1), "CREATE TEMPORARY TABLE temporary_table_1 (col1 INTEGER)" @@ -480,8 +480,8 @@ class TableTest(TestBase, AssertsCompiledSQL): TypeError, assign ) - - + + class ColumnDefinitionTest(TestBase): """Test Column() construction.""" @@ -570,4 +570,3 @@ class ColumnOptionsTest(TestBase): c.info['bar'] = 'zip' assert c.info['bar'] == 'zip' -
\ No newline at end of file diff --git a/test/sql/test_query.py b/test/sql/test_query.py index 085845bc6..6a9055887 100644 --- a/test/sql/test_query.py +++ b/test/sql/test_query.py @@ -23,7 +23,7 @@ class QueryTest(TestBase): Column('address', String(30)), test_needs_acid=True ) - + users2 = Table('u2', metadata, Column('user_id', INT, primary_key = True), Column('user_name', VARCHAR(20)), @@ -47,7 +47,7 @@ class QueryTest(TestBase): def test_insert_heterogeneous_params(self): """test that executemany parameters are asserted to match the parameter set of the first.""" - + assert_raises_message(exc.InvalidRequestError, "A value is required for bind parameter 'user_name', in parameter group 2", users.insert().execute, @@ -87,10 +87,10 @@ class QueryTest(TestBase): comp = ins.compile(engine, column_keys=list(values)) if not set(values).issuperset(c.key for c in table.primary_key): assert comp.returning - + result = engine.execute(table.insert(), **values) ret = values.copy() - + for col, id in zip(table.primary_key, result.inserted_primary_key): ret[col.key] = id @@ -104,7 +104,7 @@ class QueryTest(TestBase): if testing.against('firebird', 'postgresql', 'oracle', 'mssql'): assert testing.db.dialect.implicit_returning - + if testing.db.dialect.implicit_returning: test_engines = [ engines.testing_engine(options={'implicit_returning':False}), @@ -112,7 +112,7 @@ class QueryTest(TestBase): ] else: test_engines = [testing.db] - + for engine in test_engines: metadata = MetaData() for supported, table, values, assertvalues in [ @@ -208,14 +208,14 @@ class QueryTest(TestBase): ] else: test_engines = [testing.db] - + for engine in test_engines: - + r = engine.execute(users.insert(), {'user_name':'jack'}, ) assert r.closed - + def test_row_iteration(self): users.insert().execute( {'user_id':7, 'user_name':'jack'}, @@ -245,25 +245,25 @@ class QueryTest(TestBase): @testing.fails_on('firebird', "kinterbasdb doesn't send full type information") def test_order_by_label(self): """test that a label within an ORDER BY works on each backend. - + This test should be modified to support [ticket:1068] when that ticket is implemented. For now, you need to put the actual string in the ORDER BY. - + """ users.insert().execute( {'user_id':7, 'user_name':'jack'}, {'user_id':8, 'user_name':'ed'}, {'user_id':9, 'user_name':'fred'}, ) - + concat = ("test: " + users.c.user_name).label('thedata') print select([concat]).order_by("thedata") eq_( select([concat]).order_by("thedata").execute().fetchall(), [("test: ed",), ("test: fred",), ("test: jack",)] ) - + eq_( select([concat]).order_by("thedata").execute().fetchall(), [("test: ed",), ("test: fred",), ("test: jack",)] @@ -285,8 +285,8 @@ class QueryTest(TestBase): [("test: ed",), ("test: fred",), ("test: jack",)] ) go() - - + + def test_row_comparison(self): users.insert().execute(user_id = 7, user_name = 'jack') rp = users.select().execute().first() @@ -311,10 +311,10 @@ class QueryTest(TestBase): for pickle in False, True: for use_labels in False, True: result = users.select(use_labels=use_labels).order_by(users.c.user_id).execute().fetchall() - + if pickle: result = util.pickle.loads(util.pickle.dumps(result)) - + eq_( result, [(7, "jack"), (8, "ed"), (9, "fred")] @@ -325,27 +325,27 @@ class QueryTest(TestBase): else: eq_(result[0]['user_id'], 7) eq_(result[0].keys(), ["user_id", "user_name"]) - + eq_(result[0][0], 7) eq_(result[0][users.c.user_id], 7) eq_(result[0][users.c.user_name], 'jack') - + if use_labels: assert_raises(exc.NoSuchColumnError, lambda: result[0][addresses.c.user_id]) else: # test with a different table. name resolution is # causing 'user_id' to match when use_labels wasn't used. eq_(result[0][addresses.c.user_id], 7) - + assert_raises(exc.NoSuchColumnError, lambda: result[0]['fake key']) assert_raises(exc.NoSuchColumnError, lambda: result[0][addresses.c.address_id]) - + @testing.requires.boolean_col_expressions def test_or_and_as_columns(self): true, false = literal(True), literal(False) - + eq_(testing.db.execute(select([and_(true, false)])).scalar(), False) eq_(testing.db.execute(select([and_(true, true)])).scalar(), True) eq_(testing.db.execute(select([or_(true, false)])).scalar(), True) @@ -359,7 +359,7 @@ class QueryTest(TestBase): row = testing.db.execute(select([or_(true, false).label("x"), and_(true, false).label("y")])).first() assert row.x == True assert row.y == False - + def test_fetchmany(self): users.insert().execute(user_id = 7, user_name = 'jack') users.insert().execute(user_id = 8, user_name = 'ed') @@ -394,7 +394,7 @@ class QueryTest(TestBase): ), [(5,)]), ): eq_(expr.execute().fetchall(), result) - + @testing.fails_on("firebird", "see dialect.test_firebird:MiscTest.test_percents_in_text") @testing.fails_on("oracle", "neither % nor %% are accepted") @testing.fails_on("informix", "neither % nor %% are accepted") @@ -410,7 +410,7 @@ class QueryTest(TestBase): (text("select 'hello % world'"), "hello % world") ): eq_(testing.db.scalar(expr), result) - + def test_ilike(self): users.insert().execute( {'user_id':1, 'user_name':'one'}, @@ -642,7 +642,7 @@ class QueryTest(TestBase): self.assert_(r[0:1] == (1,)) self.assert_(r[1:] == (2, 'foo@bar.com')) self.assert_(r[:-1] == (1, 2)) - + def test_column_accessor(self): users.insert().execute(user_id=1, user_name='john') users.insert().execute(user_id=2, user_name='jack') @@ -651,11 +651,11 @@ class QueryTest(TestBase): r = users.select(users.c.user_id==2).execute().first() self.assert_(r.user_id == r['user_id'] == r[users.c.user_id] == 2) self.assert_(r.user_name == r['user_name'] == r[users.c.user_name] == 'jack') - + r = text("select * from query_users where user_id=2", bind=testing.db).execute().first() self.assert_(r.user_id == r['user_id'] == r[users.c.user_id] == 2) self.assert_(r.user_name == r['user_name'] == r[users.c.user_name] == 'jack') - + # test a little sqlite weirdness - with the UNION, # cols come back as "query_users.user_id" in cursor.description r = text("select query_users.user_id, query_users.user_name from query_users " @@ -682,14 +682,14 @@ class QueryTest(TestBase): users.insert(), {'user_id':1, 'user_name':'ed'} ) - + eq_(r.lastrowid, 1) - - + + def test_graceful_fetch_on_non_rows(self): """test that calling fetchone() etc. on a result that doesn't return rows fails gracefully. - + """ # these proxies don't work with no cursor.description present. @@ -709,7 +709,7 @@ class QueryTest(TestBase): getattr(result, meth), ) trans.rollback() - + def test_no_inserted_pk_on_non_insert(self): result = testing.db.execute("select * from query_users") assert_raises_message( @@ -717,7 +717,7 @@ class QueryTest(TestBase): r"Statement is not an insert\(\) expression construct.", getattr, result, 'inserted_primary_key' ) - + @testing.requires.returning def test_no_inserted_pk_on_returning(self): result = testing.db.execute(users.insert().returning(users.c.user_id, users.c.user_name)) @@ -726,7 +726,7 @@ class QueryTest(TestBase): r"Can't call inserted_primary_key when returning\(\) is used.", getattr, result, 'inserted_primary_key' ) - + def test_fetchone_til_end(self): result = testing.db.execute("select * from query_users") eq_(result.fetchone(), None) @@ -738,17 +738,17 @@ class QueryTest(TestBase): def test_result_case_sensitivity(self): """test name normalization for result sets.""" - + row = testing.db.execute( select([ literal_column("1").label("case_insensitive"), literal_column("2").label("CaseSensitive") ]) ).first() - + assert row.keys() == ["case_insensitive", "CaseSensitive"] - + def test_row_as_args(self): users.insert().execute(user_id=1, user_name='john') r = users.select(users.c.user_id==1).execute().first() @@ -761,12 +761,12 @@ class QueryTest(TestBase): r = users.select().execute() users2.insert().execute(list(r)) assert users2.select().execute().fetchall() == [(1, 'john'), (2, 'ed')] - + users2.delete().execute() r = users.select().execute() users2.insert().execute(*list(r)) assert users2.select().execute().fetchall() == [(1, 'john'), (2, 'ed')] - + def test_ambiguous_column(self): users.insert().execute(user_id=1, user_name='john') r = users.outerjoin(addresses).select().execute().first() @@ -782,7 +782,7 @@ class QueryTest(TestBase): "Ambiguous column name", lambda: r['user_id'] ) - + result = users.outerjoin(addresses).select().execute() result = base.BufferedColumnResultProxy(result.context) r = result.first() @@ -821,7 +821,7 @@ class QueryTest(TestBase): users.insert().execute(user_id=1, user_name='foo') r = users.select().execute().first() eq_(len(r), 2) - + r = testing.db.execute('select user_name, user_id from query_users').first() eq_(len(r), 2) r = testing.db.execute('select user_name from query_users').first() @@ -924,10 +924,10 @@ class QueryTest(TestBase): "uses sql-92 rules") def test_bind_in(self): """test calling IN against a bind parameter. - + this isn't allowed on several platforms since we generate ? = ?. - + """ users.insert().execute(user_id = 7, user_name = 'jack') users.insert().execute(user_id = 8, user_name = 'fred') @@ -940,7 +940,7 @@ class QueryTest(TestBase): assert len(r) == 3 r = s.execute(search_key=None).fetchall() assert len(r) == 0 - + @testing.emits_warning('.*empty sequence.*') @testing.fails_on('firebird', 'uses sql-92 bind rules') def test_literal_in(self): @@ -953,15 +953,15 @@ class QueryTest(TestBase): s = users.select(not_(literal("john").in_([]))) r = s.execute().fetchall() assert len(r) == 3 - - + + @testing.emits_warning('.*empty sequence.*') @testing.requires.boolean_col_expressions def test_in_filtering_advanced(self): """test the behavior of the in_() function when comparing against an empty collection, specifically that a proper boolean value is generated. - + """ users.insert().execute(user_id = 7, user_name = 'jack') @@ -980,11 +980,11 @@ class QueryTest(TestBase): class PercentSchemaNamesTest(TestBase): """tests using percent signs, spaces in table and column names. - + Doesn't pass for mysql, postgresql, but this is really a SQLAlchemy bug - we should be escaping out %% signs for this operation the same way we do for text() and column labels. - + """ @classmethod @@ -999,11 +999,11 @@ class PercentSchemaNamesTest(TestBase): def teardown(self): percent_table.delete().execute() - + @classmethod def teardown_class(cls): metadata.drop_all() - + def test_single_roundtrip(self): percent_table.insert().execute( {'percent%':5, 'spaces % more spaces':12}, @@ -1018,7 +1018,7 @@ class PercentSchemaNamesTest(TestBase): {'percent%':11, 'spaces % more spaces':9}, ) self._assert_table() - + @testing.crashes('mysql+mysqldb', 'MySQLdb handles executemany() inconsistently vs. execute()') def test_executemany_roundtrip(self): percent_table.insert().execute( @@ -1030,7 +1030,7 @@ class PercentSchemaNamesTest(TestBase): {'percent%':11, 'spaces % more spaces':9}, ) self._assert_table() - + def _assert_table(self): for table in (percent_table, percent_table.alias()): eq_( @@ -1073,9 +1073,9 @@ class PercentSchemaNamesTest(TestBase): (11, 15) ] ) - - - + + + class LimitTest(TestBase): @classmethod @@ -1106,7 +1106,7 @@ class LimitTest(TestBase): addresses.insert().execute(address_id=6, user_id=6, address='addr5') users.insert().execute(user_id=7, user_name='fido') addresses.insert().execute(address_id=7, user_id=7, address='addr5') - + @classmethod def teardown_class(cls): metadata.drop_all() @@ -1189,11 +1189,11 @@ class CompoundTest(TestBase): dict(col2="t3col2r2", col3="bbb", col4="aaa"), dict(col2="t3col2r3", col3="ccc", col4="bbb"), ]) - + @engines.close_first def teardown(self): pass - + @classmethod def teardown_class(cls): metadata.drop_all() @@ -1274,13 +1274,13 @@ class CompoundTest(TestBase): """like test_union_all, but breaks the sub-union into a subquery with an explicit column reference on the outside, more palatable to a wider variety of engines. - + """ u = union( select([t1.c.col3]), select([t1.c.col3]), ).alias() - + e = union_all( select([t1.c.col3]), select([u.c.col3]) @@ -1327,7 +1327,7 @@ class CompoundTest(TestBase): def test_except_style2(self): # same as style1, but add alias().select() to the except_(). # sqlite can handle it now. - + e = except_(union( select([t1.c.col3, t1.c.col4]), select([t2.c.col3, t2.c.col4]), @@ -1368,7 +1368,7 @@ class CompoundTest(TestBase): select([t3.c.col3], t3.c.col3 == 'ccc'), #ccc ).alias().select() ) - + eq_(e.execute().fetchall(), [('ccc',)]) eq_( e.alias().select().execute().fetchall(), @@ -1409,7 +1409,7 @@ class CompoundTest(TestBase): found = self._fetchall_sorted(u.execute()) eq_(found, wanted) - + @testing.requires.intersect def test_intersect_unions_3(self): u = intersect( @@ -1733,7 +1733,7 @@ class OperatorTest(TestBase): @classmethod def teardown_class(cls): metadata.drop_all() - + # TODO: seems like more tests warranted for this setup. def test_modulo(self): diff --git a/test/sql/test_quote.py b/test/sql/test_quote.py index e880388d7..2aa5086c6 100644 --- a/test/sql/test_quote.py +++ b/test/sql/test_quote.py @@ -96,7 +96,7 @@ class QuoteTest(TestBase, AssertsCompiledSQL): '''SELECT 1 FROM (SELECT "foo"."t1"."col1" AS "col1" FROM '''\ '''"foo"."t1") AS anon WHERE anon."col1" = :col1_1''' ) - + metadata = MetaData() t1 = Table('TableOne', metadata, Column('ColumnOne', Integer, quote=False), quote=False, schema="FooBar", quote_schema=False) @@ -105,7 +105,7 @@ class QuoteTest(TestBase, AssertsCompiledSQL): self.assert_compile(t1.select().apply_labels(), "SELECT FooBar.TableOne.ColumnOne AS "\ "FooBar_TableOne_ColumnOne FROM FooBar.TableOne" # TODO: is this what we really want here ? what if table/schema - # *are* quoted? + # *are* quoted? ) a = t1.select().alias('anon') diff --git a/test/sql/test_returning.py b/test/sql/test_returning.py index 632a739f1..2a8e6fc2f 100644 --- a/test/sql/test_returning.py +++ b/test/sql/test_returning.py @@ -10,10 +10,10 @@ class ReturningTest(TestBase, AssertsExecutionResults): def setup(self): meta = MetaData(testing.db) global table, GoofyType - + class GoofyType(TypeDecorator): impl = String - + def process_bind_param(self, value, dialect): if value is None: return None @@ -23,7 +23,7 @@ class ReturningTest(TestBase, AssertsExecutionResults): if value is None: return None return value + "BAR" - + table = Table('tables', meta, Column('id', Integer, primary_key=True, test_needs_autoincrement=True), Column('persons', Integer), @@ -31,19 +31,19 @@ class ReturningTest(TestBase, AssertsExecutionResults): Column('goofy', GoofyType(50)) ) table.create(checkfirst=True) - + def teardown(self): table.drop() - + @testing.exclude('firebird', '<', (2, 0), '2.0+ feature') @testing.exclude('postgresql', '<', (8, 2), '8.2+ feature') def test_column_targeting(self): result = table.insert().returning(table.c.id, table.c.full).execute({'persons': 1, 'full': False}) - + row = result.first() assert row[table.c.id] == row['id'] == 1 assert row[table.c.full] == row['full'] == False - + result = table.insert().values(persons=5, full=True, goofy="somegoofy").\ returning(table.c.persons, table.c.full, table.c.goofy).execute() row = result.first() @@ -52,7 +52,7 @@ class ReturningTest(TestBase, AssertsExecutionResults): eq_(row[table.c.goofy], row['goofy']) eq_(row['goofy'], "FOOsomegoofyBAR") - + @testing.fails_on('firebird', "fb can't handle returning x AS y") @testing.exclude('firebird', '<', (2, 0), '2.0+ feature') @testing.exclude('postgresql', '<', (8, 2), '8.2+ feature') @@ -76,7 +76,7 @@ class ReturningTest(TestBase, AssertsExecutionResults): returning(table.c.persons + 18).execute() row = result.first() assert row[0] == 30 - + @testing.exclude('firebird', '<', (2, 1), '2.1+ feature') @testing.exclude('postgresql', '<', (8, 2), '8.2+ feature') def test_update_returning(self): @@ -115,8 +115,8 @@ class ReturningTest(TestBase, AssertsExecutionResults): test_executemany() - - + + @testing.exclude('firebird', '<', (2, 1), '2.1+ feature') @testing.exclude('postgresql', '<', (8, 2), '8.2+ feature') @testing.fails_on_everything_except('postgresql', 'firebird') @@ -164,7 +164,7 @@ class SequenceReturningTest(TestBase): class KeyReturningTest(TestBase, AssertsExecutionResults): """test returning() works with columns that define 'key'.""" - + __unsupported_on__ = ('sqlite', 'mysql', 'maxdb', 'sybase', 'access') def setup(self): @@ -186,8 +186,8 @@ class KeyReturningTest(TestBase, AssertsExecutionResults): result = table.insert().returning(table.c.foo_id).execute(data='somedata') row = result.first() assert row[table.c.foo_id] == row['id'] == 1 - + result = table.select().execute().first() assert row[table.c.foo_id] == row['id'] == 1 - + diff --git a/test/sql/test_rowcount.py b/test/sql/test_rowcount.py index ed40f2801..fc74e8467 100644 --- a/test/sql/test_rowcount.py +++ b/test/sql/test_rowcount.py @@ -4,9 +4,9 @@ from test.lib import * class FoundRowsTest(TestBase, AssertsExecutionResults): """tests rowcount functionality""" - + __requires__ = ('sane_rowcount', ) - + @classmethod def setup_class(cls): global employees_table, metadata diff --git a/test/sql/test_selectable.py b/test/sql/test_selectable.py index 77acf896b..243c56dcf 100644 --- a/test/sql/test_selectable.py +++ b/test/sql/test_selectable.py @@ -31,7 +31,7 @@ class SelectableTest(TestBase, AssertsExecutionResults): def test_indirect_correspondence_on_labels(self): # this test depends upon 'distance' to # get the right result - + # same column three times s = select([table1.c.col1.label('c2'), table1.c.col1, @@ -48,7 +48,7 @@ class SelectableTest(TestBase, AssertsExecutionResults): def test_direct_correspondence_on_labels(self): # this test depends on labels being part # of the proxy set to get the right result - + l1, l2 = table1.c.col1.label('foo'), table1.c.col1.label('bar') sel = select([l1, l2]) @@ -85,20 +85,20 @@ class SelectableTest(TestBase, AssertsExecutionResults): j2 = jjj.alias('foo') assert j2.corresponding_column(table1.c.col1) \ is j2.c.table1_col1 - + def test_against_cloned_non_table(self): # test that corresponding column digs across # clone boundaries with anonymous labeled elements col = func.count().label('foo') sel = select([col]) - + sel2 = visitors.ReplacingCloningVisitor().traverse(sel) assert sel2.corresponding_column(col) is sel2.c.foo sel3 = visitors.ReplacingCloningVisitor().traverse(sel2) assert sel3.corresponding_column(col) is sel3.c.foo - + def test_select_on_table(self): sel = select([table1, table2], use_labels=True) @@ -153,22 +153,22 @@ class SelectableTest(TestBase, AssertsExecutionResults): def test_union_precedence(self): # conflicting column correspondence should be resolved based on # the order of the select()s in the union - + s1 = select([table1.c.col1, table1.c.col2]) s2 = select([table1.c.col2, table1.c.col1]) s3 = select([table1.c.col3, table1.c.colx]) s4 = select([table1.c.colx, table1.c.col3]) - + u1 = union(s1, s2) assert u1.corresponding_column(table1.c.col1) is u1.c.col1 assert u1.corresponding_column(table1.c.col2) is u1.c.col2 - + u1 = union(s1, s2, s3, s4) assert u1.corresponding_column(table1.c.col1) is u1.c.col1 assert u1.corresponding_column(table1.c.col2) is u1.c.col2 assert u1.corresponding_column(table1.c.colx) is u1.c.col2 assert u1.corresponding_column(table1.c.col3) is u1.c.col1 - + def test_singular_union(self): u = union(select([table1.c.col1, table1.c.col2, @@ -254,13 +254,13 @@ class SelectableTest(TestBase, AssertsExecutionResults): j = join(a, table2) criterion = a.c.acol1 == table2.c.col2 self.assert_(criterion.compare(j.onclause)) - + def test_labeled_select_correspoinding(self): l1 = select([func.max(table1.c.col1)]).label('foo') s = select([l1]) eq_(s.corresponding_column(l1), s.c.foo) - + s = select([table1.c.col1, l1]) eq_(s.corresponding_column(l1), s.c.foo) @@ -300,7 +300,7 @@ class SelectableTest(TestBase, AssertsExecutionResults): s = select([t2, t3], use_labels=True) assert_raises(exc.NoReferencedTableError, s.join, t1) - + def test_join_condition(self): m = MetaData() @@ -326,7 +326,7 @@ class SelectableTest(TestBase, AssertsExecutionResults): ]: assert expected.compare(sql_util.join_condition(left, right, a_subset=a_subset)) - + # these are ambiguous, or have no joins for left, right, a_subset in [ (t1t2, t3, None), @@ -339,7 +339,7 @@ class SelectableTest(TestBase, AssertsExecutionResults): sql_util.join_condition, left, right, a_subset=a_subset ) - + als = t2t3.alias() # test join's behavior, including natural for left, right, expected in [ @@ -370,7 +370,7 @@ class SelectableTest(TestBase, AssertsExecutionResults): "Perhaps you meant to convert the right " "side to a subquery using alias\(\)\?", t1t2.join, t2t3.select(use_labels=True)) - + class PrimaryKeyTest(TestBase, AssertsExecutionResults): @@ -488,7 +488,7 @@ class ReduceTest(TestBase, AssertsExecutionResults): t3 = Table('t3', meta, Column('t3id', Integer, ForeignKey('t2.t2id'), primary_key=True), Column('t3data', String(30))) - + eq_(util.column_set(sql_util.reduce_columns([ t1.c.t1id, t1.c.t1data, @@ -498,7 +498,7 @@ class ReduceTest(TestBase, AssertsExecutionResults): t3.c.t3data, ])), util.column_set([t1.c.t1id, t1.c.t1data, t2.c.t2data, t3.c.t3data])) - + def test_reduce_selectable(self): metadata = MetaData() @@ -514,7 +514,7 @@ class ReduceTest(TestBase, AssertsExecutionResults): eq_(util.column_set(sql_util.reduce_columns(list(s.c), s)), util.column_set([s.c.engineer_id, s.c.engineer_name, s.c.manager_id])) - + def test_reduce_aliased_join(self): metadata = MetaData() @@ -543,7 +543,7 @@ class ReduceTest(TestBase, AssertsExecutionResults): eq_(util.column_set(sql_util.reduce_columns([pjoin.c.people_person_id, pjoin.c.engineers_person_id, pjoin.c.managers_person_id])), util.column_set([pjoin.c.people_person_id])) - + def test_reduce_aliased_union(self): metadata = MetaData() @@ -567,7 +567,7 @@ class ReduceTest(TestBase, AssertsExecutionResults): item_join.c.dummy, item_join.c.child_name])), util.column_set([item_join.c.id, item_join.c.dummy, item_join.c.child_name])) - + def test_reduce_aliased_union_2(self): metadata = MetaData() @@ -597,7 +597,7 @@ class ReduceTest(TestBase, AssertsExecutionResults): select_from( page_table.join(magazine_page_table). join(classified_page_table)), - + select([ page_table.c.id, magazine_page_table.c.page_id, @@ -622,7 +622,7 @@ class ReduceTest(TestBase, AssertsExecutionResults): cast(null(), Integer).label('magazine_page_id') ]). select_from(page_table.join(magazine_page_table)), - + select([ page_table.c.id, magazine_page_table.c.page_id, @@ -684,7 +684,7 @@ class AnnotationsTest(TestBase): def __init__(self): Column.__init__(self, 'foo', Integer) _constructor = Column - + t1 = Table('t1', MetaData(), MyColumn()) s1 = t1.select() assert isinstance(t1.c.foo, MyColumn) @@ -695,14 +695,14 @@ class AnnotationsTest(TestBase): assert isinstance(s2.c.foo, Column) annot_2 = s1._annotate({}) assert isinstance(annot_2.c.foo, Column) - + def test_annotated_corresponding_column(self): table1 = table('table1', column("col1")) - + s1 = select([table1.c.col1]) t1 = s1._annotate({}) t2 = s1 - + # t1 needs to share the same _make_proxy() columns as t2, even # though it's annotated. otherwise paths will diverge once they # are corresponded against "inner" below. @@ -723,12 +723,12 @@ class AnnotationsTest(TestBase): def test_annotated_visit(self): table1 = table('table1', column("col1"), column("col2")) - + bin = table1.c.col1 == bindparam('foo', value=None) assert str(bin) == "table1.col1 = :foo" def visit_binary(b): b.right = table1.c.col2 - + b2 = visitors.cloned_traverse(bin, {}, {'binary':visit_binary}) assert str(b2) == "table1.col1 = table1.col2" @@ -739,13 +739,13 @@ class AnnotationsTest(TestBase): def visit_binary(b): b.left = bindparam('bar') - + b4 = visitors.cloned_traverse(b2, {}, {'binary':visit_binary}) assert str(b4) == ":bar = table1.col2" b5 = visitors.cloned_traverse(b3, {}, {'binary':visit_binary}) assert str(b5) == ":bar = table1.col2" - + def test_annotate_expressions(self): table1 = table('table1', column('col1'), column('col2')) @@ -760,10 +760,10 @@ class AnnotationsTest(TestBase): eq_(str(sql_util._deep_annotate(expr, {})), expected) eq_(str(sql_util._deep_annotate(expr, {}, exclude=[table1.c.col1])), expected) - + def test_deannotate(self): table1 = table('table1', column("col1"), column("col2")) - + bin = table1.c.col1 == bindparam('foo', value=None) b2 = sql_util._deep_annotate(bin, {'_orm_adapt':True}) @@ -772,7 +772,7 @@ class AnnotationsTest(TestBase): for elem in (b2._annotations, b2.left._annotations): assert '_orm_adapt' in elem - + for elem in b3._annotations, b3.left._annotations, \ b4._annotations, b4.left._annotations: assert elem == {} @@ -781,4 +781,4 @@ class AnnotationsTest(TestBase): assert b3.left is not b2.left is not bin.left assert b4.left is bin.left # since column is immutable assert b4.right is not bin.right is not b2.right is not b3.right - + diff --git a/test/sql/test_types.py b/test/sql/test_types.py index 700f7b7de..1665e35c8 100644 --- a/test/sql/test_types.py +++ b/test/sql/test_types.py @@ -22,11 +22,11 @@ class AdaptTest(TestBase): for d in dialects.__all__ if not d.startswith('_') ] - + def _all_dialects(self): return [d.base.dialect() for d in self._all_dialect_modules()] - + def _all_types(self): def types_for_mod(mod): for key in dir(mod): @@ -34,24 +34,24 @@ class AdaptTest(TestBase): if not isinstance(typ, type) or not issubclass(typ, types.TypeEngine): continue yield typ - + for typ in types_for_mod(types): yield typ for dialect in self._all_dialect_modules(): for typ in types_for_mod(dialect): yield typ - + def test_uppercase_rendering(self): """Test that uppercase types from types.py always render as their type. - + As of SQLA 0.6, using an uppercase type means you want specifically that type. If the database in use doesn't support that DDL, it (the DB backend) should raise an error - it means you should be using a lowercased (genericized) type. - + """ - + for dialect in self._all_dialects(): for type_, expected in ( (FLOAT, "FLOAT"), @@ -77,29 +77,29 @@ class AdaptTest(TestBase): compiled = types.to_instance(type_).\ compile(dialect=dialect) - + assert compiled in expected, \ "%r matches none of %r for dialect %s" % \ (compiled, expected, dialect.name) - + assert str(types.to_instance(type_)) in expected, \ "default str() of type %r not expected, %r" % \ (type_, expected) - + @testing.uses_deprecated() def test_adapt_method(self): """ensure all types have a working adapt() method, - which creates a distinct copy. - + which creates a distinct copy. + The distinct copy ensures that when we cache the adapted() form of a type against the original in a weak key dictionary, a cycle is not formed. - + This test doesn't test type-specific arguments of adapt() beyond their defaults. - + """ - + for typ in self._all_types(): if typ in (types.TypeDecorator, types.TypeEngine): continue @@ -117,8 +117,8 @@ class AdaptTest(TestBase): if k == 'impl': continue eq_(getattr(t2, k), t1.__dict__[k]) - - + + class TypeAffinityTest(TestBase): def test_type_affinity(self): for type_, affin in [ @@ -128,7 +128,7 @@ class TypeAffinityTest(TestBase): (LargeBinary(), types._Binary) ]: eq_(type_._type_affinity, affin) - + for t1, t2, comp in [ (Integer(), SmallInteger(), True), (Integer(), String(), False), @@ -169,7 +169,7 @@ class PickleMetadataTest(TestBase): Table('foo', meta, column_type) ct = loads(dumps(column_type)) mt = loads(dumps(meta)) - + class UserDefinedTest(TestBase, AssertsCompiledSQL): """tests user-defined types.""" @@ -210,37 +210,37 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): ]: for dialect_ in (dialects.postgresql, dialects.mssql, dialects.mysql): dialect_ = dialect_.dialect() - + raw_impl = types.to_instance(impl_, **kw) - + class MyType(types.TypeDecorator): impl = impl_ - + dec_type = MyType(**kw) - + eq_(dec_type.impl.__class__, raw_impl.__class__) - + raw_dialect_impl = raw_impl.dialect_impl(dialect_) dec_dialect_impl = dec_type.dialect_impl(dialect_) eq_(dec_dialect_impl.__class__, MyType) eq_(raw_dialect_impl.__class__ , dec_dialect_impl.impl.__class__) - + self.assert_compile( MyType(**kw), exp, dialect=dialect_ ) - + def test_user_defined_typedec_impl(self): class MyType(types.TypeDecorator): impl = Float - + def load_dialect_impl(self, dialect): if dialect.name == 'sqlite': return String(50) else: return super(MyType, self).load_dialect_impl(dialect) - + sl = dialects.sqlite.dialect() pg = dialects.postgresql.dialect() t = MyType() @@ -254,35 +254,35 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): t.dialect_impl(dialect=pg).impl.__class__, Float().dialect_impl(pg).__class__ ) - + @testing.provide_metadata def test_type_coerce(self): """test ad-hoc usage of custom types with type_coerce().""" - + class MyType(types.TypeDecorator): impl = String def process_bind_param(self, value, dialect): return value[0:-8] - + def process_result_value(self, value, dialect): return value + "BIND_OUT" - + t = Table('t', metadata, Column('data', String(50))) metadata.create_all() - + t.insert().values(data=type_coerce('d1BIND_OUT',MyType)).execute() eq_( select([type_coerce(t.c.data, MyType)]).execute().fetchall(), [('d1BIND_OUT', )] ) - + eq_( select([t.c.data, type_coerce(t.c.data, MyType)]).execute().fetchall(), [('d1', 'd1BIND_OUT')] ) - + eq_( select([t.c.data, type_coerce(t.c.data, MyType)]).\ where(type_coerce(t.c.data, MyType) == 'd1BIND_OUT').\ @@ -310,7 +310,7 @@ class UserDefinedTest(TestBase, AssertsCompiledSQL): execute().fetchall(), [] ) - + @classmethod def setup_class(cls): global users, metadata @@ -432,7 +432,7 @@ class UnicodeTest(TestBase, AssertsExecutionResults): Column('unicode_text', UnicodeText), ) metadata.create_all() - + @classmethod def teardown_class(cls): metadata.drop_all() @@ -440,26 +440,26 @@ class UnicodeTest(TestBase, AssertsExecutionResults): @engines.close_first def teardown(self): unicode_table.delete().execute() - + def test_native_unicode(self): """assert expected values for 'native unicode' mode""" - + if \ (testing.against('mssql+pyodbc') and not testing.db.dialect.freetds): assert testing.db.dialect.returns_unicode_strings == 'conditional' return - + if testing.against('mssql+pymssql'): assert testing.db.dialect.returns_unicode_strings == ('charset' in testing.db.url.query) return - + assert testing.db.dialect.returns_unicode_strings == \ ((testing.db.name, testing.db.driver) in \ ( ('postgresql','psycopg2'), ('postgresql','pypostgresql'), ('postgresql','pg8000'), - ('postgresql','zxjdbc'), + ('postgresql','zxjdbc'), ('mysql','oursql'), ('mysql','zxjdbc'), ('mysql','mysqlconnector'), @@ -471,14 +471,14 @@ class UnicodeTest(TestBase, AssertsExecutionResults): (testing.db.name, testing.db.driver, testing.db.dialect.returns_unicode_strings) - + def test_round_trip(self): unicodedata = u"Alors vous imaginez ma surprise, au lever du jour, "\ u"quand une drôle de petit voix m’a réveillé. Elle "\ u"disait: « S’il vous plaît… dessine-moi un mouton! »" - + unicode_table.insert().execute(unicode_varchar=unicodedata,unicode_text=unicodedata) - + x = unicode_table.select().execute().first() assert isinstance(x['unicode_varchar'], unicode) assert isinstance(x['unicode_text'], unicode) @@ -488,7 +488,7 @@ class UnicodeTest(TestBase, AssertsExecutionResults): def test_round_trip_executemany(self): # cx_oracle was producing different behavior for cursor.executemany() # vs. cursor.execute() - + unicodedata = u"Alors vous imaginez ma surprise, au lever du jour, quand "\ u"une drôle de petit voix m’a réveillé. "\ u"Elle disait: « S’il vous plaît… dessine-moi un mouton! »" @@ -512,12 +512,12 @@ class UnicodeTest(TestBase, AssertsExecutionResults): u"Elle disait: « S’il vous plaît… dessine-moi un mouton! »" unicode_table.insert().execute(unicode_varchar=unicodedata,unicode_text=unicodedata) - + x = union( select([unicode_table.c.unicode_varchar]), select([unicode_table.c.unicode_varchar]) ).execute().first() - + assert isinstance(x['unicode_varchar'], unicode) eq_(x['unicode_varchar'], unicodedata) @@ -529,13 +529,13 @@ class UnicodeTest(TestBase, AssertsExecutionResults): def test_unicode_warnings(self): """test the warnings raised when SQLA must coerce unicode binds, *and* is using the Unicode type. - + """ unicodedata = u"Alors vous imaginez ma surprise, au lever du jour, quand "\ u"une drôle de petit voix m’a réveillé. "\ u"Elle disait: « S’il vous plaît… dessine-moi un mouton! »" - + # using Unicode explicly - warning should be emitted u = Unicode() uni = u.dialect_impl(testing.db.dialect).bind_processor(testing.db.dialect) @@ -557,14 +557,14 @@ class UnicodeTest(TestBase, AssertsExecutionResults): assert_raises(exc.SAWarning, uni, 'x') assert isinstance(uni(unicodedata), str) # end Py2K - + eq_(uni(unicodedata), unicodedata.encode('utf-8')) - + # using convert unicode at engine level - # this should not be raising a warning unicode_engine = engines.utf8_engine(options={'convert_unicode':True,}) unicode_engine.dialect.supports_unicode_binds = False - + s = String() uni = s.dialect_impl(unicode_engine.dialect).bind_processor(unicode_engine.dialect) # this is not the unicode type - no warning @@ -575,36 +575,36 @@ class UnicodeTest(TestBase, AssertsExecutionResults): uni('x') assert isinstance(uni(unicodedata), str) # end Py2K - + eq_(uni(unicodedata), unicodedata.encode('utf-8')) - + @testing.fails_if( lambda: testing.db_spec("postgresql+pg8000")(testing.db) and util.py3k, "pg8000 appropriately does not accept 'bytes' for a VARCHAR column." ) def test_ignoring_unicode_error(self): """checks String(unicode_error='ignore') is passed to underlying codec.""" - + unicodedata = u"Alors vous imaginez ma surprise, au lever du jour, quand "\ u"une drôle de petit voix m’a réveillé. "\ u"Elle disait: « S’il vous plaît… dessine-moi un mouton! »" - + asciidata = unicodedata.encode('ascii', 'ignore') - + m = MetaData() table = Table('unicode_err_table', m, Column('sort', Integer), Column('plain_varchar_no_coding_error', \ String(248, convert_unicode='force', unicode_error='ignore')) ) - + m2 = MetaData() utf8_table = Table('unicode_err_table', m2, Column('sort', Integer), Column('plain_varchar_no_coding_error', \ String(248, convert_unicode=True)) ) - + engine = engines.testing_engine(options={'encoding':'ascii'}) m.create_all(engine) try: @@ -619,7 +619,7 @@ class UnicodeTest(TestBase, AssertsExecutionResults): # switch to utf-8 engine.dialect.encoding = 'utf-8' from binascii import hexlify - + # the row that we put in was stored as hexlified ascii row = engine.execute(utf8_table.select()).first() x = row['plain_varchar_no_coding_error'] @@ -629,7 +629,7 @@ class UnicodeTest(TestBase, AssertsExecutionResults): a = hexlify(x) b = hexlify(asciidata) eq_(a, b) - + # insert another row which will be stored with # utf-8 only chars engine.execute( @@ -649,7 +649,7 @@ class UnicodeTest(TestBase, AssertsExecutionResults): ascii_row = result.fetchone() utf8_row = result.fetchone() result.close() - + x = ascii_row['plain_varchar_no_coding_error'] # on python3 "x" comes back as string (i.e. unicode), # hexlify requires bytes @@ -671,7 +671,7 @@ class UnicodeTest(TestBase, AssertsExecutionResults): else: a = hexlify(x) eq_(a, b) - + finally: m.drop_all(engine) @@ -692,11 +692,11 @@ class EnumTest(TestBase): ) metadata.create_all() - + def teardown(self): enum_table.delete().execute() non_native_enum_table.delete().execute() - + @classmethod def teardown_class(cls): metadata.drop_all() @@ -713,7 +713,7 @@ class EnumTest(TestBase): {'id':2, 'someenum':'two'}, {'id':3, 'someenum':'one'}, ]) - + eq_( enum_table.select().order_by(enum_table.c.id).execute().fetchall(), [ @@ -739,7 +739,7 @@ class EnumTest(TestBase): (3, 'one'), ] ) - + def test_adapt(self): from sqlalchemy.dialects.postgresql import ENUM e1 = Enum('one','two','three', native_enum=False) @@ -749,7 +749,7 @@ class EnumTest(TestBase): e1 = Enum('one','two','three', name='foo', schema='bar') eq_(e1.adapt(ENUM).name, 'foo') eq_(e1.adapt(ENUM).schema, 'bar') - + @testing.fails_on('mysql+mysqldb', "MySQL seems to issue a 'data truncated' warning.") def test_constraint(self): assert_raises(exc.DBAPIError, @@ -764,7 +764,7 @@ class EnumTest(TestBase): non_native_enum_table.insert().execute, {'id':4, 'someenum':'four'} ) - + class BinaryTest(TestBase, AssertsExecutionResults): __excluded_on__ = ( ('mysql', '<', (4, 1, 1)), # screwy varbinary types @@ -786,7 +786,7 @@ class BinaryTest(TestBase, AssertsExecutionResults): if value: value.stuff = 'this is the right stuff' return value - + metadata = MetaData(testing.db) binary_table = Table('binary_table', metadata, Column('primary_id', Integer, primary_key=True, test_needs_autoincrement=True), @@ -855,15 +855,15 @@ class BinaryTest(TestBase, AssertsExecutionResults): 'data, not really known how to make this work') def test_comparison(self): """test that type coercion occurs on comparison for binary""" - + expr = binary_table.c.data == 'foo' assert isinstance(expr.right.type, LargeBinary) - + data = os.urandom(32) binary_table.insert().execute(data=data) eq_(binary_table.select().where(binary_table.c.data==data).alias().count().scalar(), 1) - - + + def load_stream(self, name): f = os.path.join(os.path.dirname(__file__), "..", name) return open(f, mode='rb').read() @@ -886,16 +886,16 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): return process def adapt_operator(self, op): return {operators.add:operators.sub, operators.sub:operators.add}.get(op, op) - + class MyTypeDec(types.TypeDecorator): impl = String - + def process_bind_param(self, value, dialect): return "BIND_IN" + str(value) def process_result_value(self, value, dialect): return value + "BIND_OUT" - + meta = MetaData(testing.db) test_table = Table('test', meta, Column('id', Integer, primary_key=True), @@ -951,14 +951,14 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): expr = test_table.c.bvalue == bindparam("somevalue") eq_(expr.right.type._type_affinity, String) - + eq_( testing.db.execute(test_table.select().where(expr), {"somevalue":"foo"}).fetchall(), [(1, 'somedata', datetime.date(2007, 10, 15), 25, 'BIND_INfooBIND_OUT')] ) - + def test_literal_adapt(self): # literals get typed based on the types dictionary, unless # compatible with the left side type @@ -974,8 +974,8 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): expr = column('foo', CHAR) == "asdf" eq_(expr.right.type.__class__, CHAR) - - + + @testing.fails_on('firebird', 'Data type unknown on the parameter') def test_operator_adapt(self): """test type-based overloading of operators""" @@ -996,7 +996,7 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): assert testing.db.execute(select([expr.label('foo')])).scalar() == 21 expr = test_table.c.avalue + literal(40, type_=MyCustomType) - + # + operator converted to - # value is calculated as: (250 - (40 * 10)) / 10 == -15 assert testing.db.execute(select([expr.label('foo')])).scalar() == -15 @@ -1007,10 +1007,10 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): def test_typedec_operator_adapt(self): expr = test_table.c.bvalue + "hi" - + assert expr.type.__class__ is MyTypeDec assert expr.right.type.__class__ is MyTypeDec - + eq_( testing.db.execute(select([expr.label('foo')])).scalar(), "BIND_INfooBIND_INhiBIND_OUT" @@ -1019,7 +1019,7 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): def test_typedec_righthand_coercion(self): class MyTypeDec(types.TypeDecorator): impl = String - + def process_bind_param(self, value, dialect): return "BIND_IN" + str(value) @@ -1028,34 +1028,34 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): tab = table('test', column('bvalue', MyTypeDec)) expr = tab.c.bvalue + 6 - + self.assert_compile( expr, "test.bvalue || :bvalue_1", use_default_dialect=True ) - + assert expr.type.__class__ is MyTypeDec eq_( testing.db.execute(select([expr.label('foo')])).scalar(), "BIND_INfooBIND_IN6BIND_OUT" ) - - + + def test_bind_typing(self): from sqlalchemy.sql import column - + class MyFoobarType(types.UserDefinedType): pass - + class Foo(object): pass - + # unknown type + integer, right hand bind # is an Integer expr = column("foo", MyFoobarType) + 5 assert expr.right.type._type_affinity is types.Integer - + # untyped bind - it gets assigned MyFoobarType expr = column("foo", MyFoobarType) + bindparam("foo") assert expr.right.type._type_affinity is MyFoobarType @@ -1067,30 +1067,30 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): # coerces to the left expr = column("foo", MyFoobarType) + Foo() assert expr.right.type._type_affinity is MyFoobarType - + # including for non-commutative ops expr = column("foo", MyFoobarType) - Foo() assert expr.right.type._type_affinity is MyFoobarType expr = column("foo", MyFoobarType) - datetime.date(2010, 8, 25) assert expr.right.type._type_affinity is types.Date - + def test_date_coercion(self): from sqlalchemy.sql import column - + expr = column('bar', types.NULLTYPE) - column('foo', types.TIMESTAMP) eq_(expr.type._type_affinity, types.NullType) - + expr = func.sysdate() - column('foo', types.TIMESTAMP) eq_(expr.type._type_affinity, types.Interval) expr = func.current_date() - column('foo', types.TIMESTAMP) eq_(expr.type._type_affinity, types.Interval) - + def test_numerics_coercion(self): from sqlalchemy.sql import column import operator - + for op in ( operator.add, operator.mul, @@ -1114,15 +1114,15 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): str(column('a', types.NullType()) + column('b', types.NullType())), "a + b" ) - + def test_expression_typing(self): expr = column('bar', Integer) - 3 - + eq_(expr.type._type_affinity, Integer) expr = bindparam('bar') + bindparam('foo') eq_(expr.type, types.NULLTYPE) - + def test_distinct(self): s = select([distinct(test_table.c.avalue)]) eq_(testing.db.execute(s).scalar(), 25) @@ -1132,12 +1132,12 @@ class ExpressionTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): assert distinct(test_table.c.data).type == test_table.c.data.type assert test_table.c.data.distinct().type == test_table.c.data.type - + class CompileTest(TestBase, AssertsCompiledSQL): def test_default_compile(self): """test that the base dialect of the type object is used for default compilation. - + """ for type_, expected in ( (String(), "VARCHAR"), @@ -1207,8 +1207,8 @@ class DateTest(TestBase, AssertsExecutionResults): datetime.time(23, 59, 59, time_micro)), (10, 'colber', None, None, None), ] - - + + fnames = ['user_id', 'user_name', 'user_datetime', 'user_date', 'user_time'] @@ -1300,10 +1300,10 @@ class NumericTest(TestBase): def setup(self): global metadata metadata = MetaData(testing.db) - + def teardown(self): metadata.drop_all() - + @testing.emits_warning(r".*does \*not\* support Decimal objects natively") def _do_test(self, type_, input_, output, filter_ = None): t = Table('t', metadata, Column('x', type_)) @@ -1318,7 +1318,7 @@ class NumericTest(TestBase): #print result #print output eq_(result, output) - + def test_numeric_as_decimal(self): self._do_test( Numeric(precision=8, scale=4), @@ -1354,7 +1354,7 @@ class NumericTest(TestBase): [15.7563], filter_ = lambda n:n is not None and round(n, 5) or None ) - + @testing.fails_on('mssql+pymssql', 'FIXME: improve pymssql dec handling') def test_precision_decimal(self): numbers = set([ @@ -1362,7 +1362,7 @@ class NumericTest(TestBase): decimal.Decimal("0.004354"), decimal.Decimal("900.0"), ]) - + self._do_test( Numeric(precision=18, scale=12), numbers, @@ -1372,12 +1372,12 @@ class NumericTest(TestBase): @testing.fails_on('mssql+pymssql', 'FIXME: improve pymssql dec handling') def test_enotation_decimal(self): """test exceedingly small decimals. - + Decimal reports values with E notation when the exponent is greater than 6. - + """ - + numbers = set([ decimal.Decimal('1E-2'), decimal.Decimal('1E-3'), @@ -1397,7 +1397,7 @@ class NumericTest(TestBase): numbers, numbers ) - + @testing.fails_on("sybase+pyodbc", "Don't know how do get these values through FreeTDS + Sybase") @testing.fails_on("firebird", "Precision must be from 1 to 18") @@ -1417,7 +1417,7 @@ class NumericTest(TestBase): numbers, numbers ) - + @testing.fails_on('sqlite', 'TODO') @testing.fails_on('postgresql+pg8000', 'TODO') @testing.fails_on("firebird", "Precision must be from 1 to 18") @@ -1434,11 +1434,11 @@ class NumericTest(TestBase): numbers, numbers ) - + class NumericRawSQLTest(TestBase): """Test what DBAPIs and dialects return without any typing information supplied at the SQLA level. - + """ def _fixture(self, metadata, type, data): t = Table('t', metadata, @@ -1446,7 +1446,7 @@ class NumericRawSQLTest(TestBase): ) metadata.create_all() t.insert().execute(val=data) - + @testing.fails_on('sqlite', "Doesn't provide Decimal results natively") @testing.provide_metadata def test_decimal_fp(self): @@ -1475,16 +1475,16 @@ class NumericRawSQLTest(TestBase): t = self._fixture(metadata, Float, 46.583) val = testing.db.execute("select val from t").scalar() assert isinstance(val, float) - + # some DBAPIs have unusual float handling if testing.against('oracle+cx_oracle', 'mysql+oursql'): eq_(round_decimal(val, 3), 46.583) else: eq_(val, 46.583) - - - - + + + + class IntervalTest(TestBase, AssertsExecutionResults): @classmethod def setup_class(cls): @@ -1529,8 +1529,8 @@ class IntervalTest(TestBase, AssertsExecutionResults): eq_(row['native_interval'], None) eq_(row['native_interval_args'], None) eq_(row['non_native_interval'], None) - - + + class BooleanTest(TestBase, AssertsExecutionResults): @classmethod def setup_class(cls): @@ -1542,14 +1542,14 @@ class BooleanTest(TestBase, AssertsExecutionResults): Column('unconstrained_value', Boolean(create_constraint=False)), ) bool_table.create() - + @classmethod def teardown_class(cls): bool_table.drop() - + def teardown(self): bool_table.delete().execute() - + def test_boolean(self): bool_table.insert().execute(id=1, value=True) bool_table.insert().execute(id=2, value=False) @@ -1573,11 +1573,11 @@ class BooleanTest(TestBase, AssertsExecutionResults): eq_(res3, [(1, True), (2, False), (3, True), (4, True), (5, True), (6, None)]) - + # ensure we're getting True/False, not just ints assert res3[0][1] is True assert res3[1][1] is False - + @testing.fails_on('mysql', "The CHECK clause is parsed but ignored by all storage engines.") @testing.fails_on('mssql', @@ -1592,11 +1592,11 @@ class BooleanTest(TestBase, AssertsExecutionResults): def test_unconstrained(self): testing.db.execute( "insert into booltest (id, unconstrained_value) values (1, 5)") - + class PickleTest(TestBase): def test_eq_comparison(self): p1 = PickleType() - + for obj in ( {'1':'2'}, pickleable.Bar(5, 6), @@ -1608,7 +1608,7 @@ class PickleTest(TestBase): p1.compare_values, pickleable.BrokenComparable('foo'), pickleable.BrokenComparable('foo')) - + def test_nonmutable_comparison(self): p1 = PickleType() @@ -1618,7 +1618,7 @@ class PickleTest(TestBase): pickleable.OldSchool(10, 11) ): assert p1.compare_values(p1.copy_value(obj), obj) - + class CallableTest(TestBase): @classmethod def setup_class(cls): diff --git a/test/sql/test_unicode.py b/test/sql/test_unicode.py index 2eda4ffa8..d6757caf1 100644 --- a/test/sql/test_unicode.py +++ b/test/sql/test_unicode.py @@ -122,13 +122,13 @@ class EscapesDefaultsTest(testing.TestBase): try: engine = metadata.bind - + # reset the identifier preparer, so that we can force it to cache # a unicode identifier engine.dialect.identifier_preparer = engine.dialect.preparer(engine.dialect) select([column(u'special_col')]).select_from(t1).execute().close() assert isinstance(engine.dialect.identifier_preparer.format_sequence(Sequence('special_col')), unicode) - + # now execute, run the sequence. it should run in u"Special_col.nextid" or similar as # a unicode object; cx_oracle asserts that this is None or a String (postgresql lets it pass thru). # ensure that executioncontext._exec_default() is encoding. diff --git a/test/zblog/test_zblog.py b/test/zblog/test_zblog.py index ec6402a6e..0ef1293e9 100644 --- a/test/zblog/test_zblog.py +++ b/test/zblog/test_zblog.py @@ -12,7 +12,7 @@ class ZBlogTest(TestBase, AssertsExecutionResults): def create_tables(cls): tables.metadata.drop_all(bind=testing.db) tables.metadata.create_all(bind=testing.db) - + @classmethod def drop_tables(cls): tables.metadata.drop_all(bind=testing.db) @@ -33,7 +33,7 @@ class SavePostTest(ZBlogTest): @classmethod def setup_class(cls): super(SavePostTest, cls).setup_class() - + mappers.zblog_mappers() global blog_id, user_id s = create_session(bind=testing.db) @@ -54,7 +54,7 @@ class SavePostTest(ZBlogTest): def test_attach_noautoflush(self): """Test pending backref behavior.""" - + s = create_session(bind=testing.db, autoflush=False) s.begin() |