Here are the examples of the python api sqlalchemy.testing.is_not taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
50 Examples
3
Source : test_parseconnect.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_copy(self):
url1 = url.make_url(
"dialect://user:pass@host/db?arg1%3D=param1&arg2=param+2"
)
url2 = copy.copy(url1)
eq_(url1, url2)
is_not(url1, url2)
def test_deepcopy(self):
3
Source : test_parseconnect.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_deepcopy(self):
url1 = url.make_url(
"dialect://user:pass@host/db?arg1%3D=param1&arg2=param+2"
)
url2 = copy.deepcopy(url1)
eq_(url1, url2)
is_not(url1, url2)
is_not(url1.query, url2.query) # immutabledict of immutable k/v,
# but it copies it on constructor
# in any case if params are present
@testing.combinations(
3
Source : test_pool.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_recycle_on_invalidate(self):
p = self._queuepool_fixture(pool_size=1, max_overflow=0)
c1 = p.connect()
c_ref = weakref.ref(c1.dbapi_connection)
c1.close()
c2 = p.connect()
is_(c2.dbapi_connection, c_ref())
c2_rec = c2._connection_record
p._invalidate(c2)
assert c2_rec.dbapi_connection is None
c2.close()
time.sleep(0.5)
c3 = p.connect()
is_not(c3.dbapi_connection, c_ref())
@testing.requires.timing_intensive
3
Source : test_reflection.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def check_table_column(self, table, name, text, persisted):
is_true(name in table.columns)
col = table.columns[name]
is_not(col.computed, None)
is_instance_of(col.computed, Computed)
eq_(self.normalize(str(col.computed.sqltext)), text)
if testing.requires.computed_columns_reflect_persisted.enabled:
eq_(col.computed.persisted, persisted)
else:
is_(col.computed.persisted, None)
def test_table_reflection(self):
3
Source : test_engine_py3k.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
async def test_dispose(self, async_engine):
c1 = await async_engine.connect()
c2 = await async_engine.connect()
await c1.close()
await c2.close()
p1 = async_engine.pool
if isinstance(p1, AsyncAdaptedQueuePool):
eq_(async_engine.pool.checkedin(), 2)
await async_engine.dispose()
if isinstance(p1, AsyncAdaptedQueuePool):
eq_(async_engine.pool.checkedin(), 0)
is_not(p1, async_engine.pool)
@testing.requires.independent_connections
3
Source : test_engine_py3k.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_regenerate_connection(self, connection):
async_connection = AsyncConnection._retrieve_proxy_for_target(
connection
)
a2 = AsyncConnection._retrieve_proxy_for_target(connection)
is_(async_connection, a2)
is_not(async_connection, None)
is_(async_connection.engine, a2.engine)
is_not(async_connection.engine, None)
@testing.requires.predictable_gc
3
Source : test_baked.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_chained_add(self):
User = self.classes.User
session = fixture_session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
q2 = q1.with_criteria(l2)
is_not(q2, q1)
self._assert_cache_key(q1._cache_key, [l1])
self._assert_cache_key(q2._cache_key, [l1, l2])
def test_chained_add_operator(self):
3
Source : test_typed_mapping.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_mc_duplication_plain(self, decl_base):
class MixinOne:
name: Mapped[str] = mapped_column()
class A(MixinOne, decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
class B(MixinOne, decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(primary_key=True)
is_not(A.__table__.c.name, B.__table__.c.name)
def test_mc_duplication_declared_attr(self, decl_base):
3
Source : test_typed_mapping.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_mc_duplication_declared_attr(self, decl_base):
class MixinOne:
@declared_attr
def name(cls) -> Mapped[str]:
return mapped_column()
class A(MixinOne, decl_base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
class B(MixinOne, decl_base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(primary_key=True)
is_not(A.__table__.c.name, B.__table__.c.name)
def test_relationship_requires_declared_attr(self, decl_base):
3
Source : test_attributes.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_bulk_replace_resets_empty(self):
A = self.A
a1 = A()
state = attributes.instance_state(a1)
existing = a1.bs
is_(state._empty_collections["bs"], existing)
is_not(existing._sa_adapter, None)
a1.bs = [] # replaces previous "empty" collection
not_in("bs", state._empty_collections) # empty is replaced
is_(existing._sa_adapter, None)
def test_assert_false_on_default_value(self):
3
Source : test_transaction.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_no_autobegin_after_explicit_commit(self):
User, users = self.classes.User, self.tables.users
self.mapper_registry.map_imperatively(User, users)
session = fixture_session()
session.add(User(name="ed"))
session.get_transaction().commit()
is_(session.get_transaction(), None)
session.connection()
is_not(session.get_transaction(), None)
class _LocalFixture(FixtureTest):
3
Source : test_compare.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_generative_cache_key_regen(self):
t1 = table("t1", column("a"), column("b"))
s1 = select(t1)
ck1 = s1._generate_cache_key()
s2 = s1.where(t1.c.a == 5)
ck2 = s2._generate_cache_key()
ne_(ck1, ck2)
is_not(ck1, None)
is_not(ck2, None)
def test_generative_cache_key_regen_w_del(self):
3
Source : test_external_traversal.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_traverse_memoizes_w_columns(self):
t1a = t1.alias()
adapter = sql_util.ColumnAdapter(t1a, anonymize_labels=True)
expr = select(t1a.c.col1).label("x")
expr_adapted = adapter.traverse(expr)
is_not(expr, expr_adapted)
is_(adapter.columns[expr], expr_adapted)
def test_traverse_memoizes_w_itself(self):
3
Source : test_external_traversal.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_traverse_memoizes_w_itself(self):
t1a = t1.alias()
adapter = sql_util.ColumnAdapter(t1a, anonymize_labels=True)
expr = select(t1a.c.col1).label("x")
expr_adapted = adapter.traverse(expr)
is_not(expr, expr_adapted)
is_(adapter.traverse(expr), expr_adapted)
def test_columns_memoizes_w_itself(self):
3
Source : test_external_traversal.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_columns_memoizes_w_itself(self):
t1a = t1.alias()
adapter = sql_util.ColumnAdapter(t1a, anonymize_labels=True)
expr = select(t1a.c.col1).label("x")
expr_adapted = adapter.columns[expr]
is_not(expr, expr_adapted)
is_(adapter.columns[expr], expr_adapted)
def test_wrapping_fallthrough(self):
3
Source : test_external_traversal.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_columns(self):
s = t1.select()
self.assert_compile(
s, "SELECT table1.col1, table1.col2, " "table1.col3 FROM table1"
)
select_copy = s.add_columns(column("yyy"))
self.assert_compile(
select_copy,
"SELECT table1.col1, table1.col2, " "table1.col3, yyy FROM table1",
)
is_not(s.selected_columns, select_copy.selected_columns)
is_not(s._raw_columns, select_copy._raw_columns)
self.assert_compile(
s, "SELECT table1.col1, table1.col2, " "table1.col3 FROM table1"
)
def test_froms(self):
3
Source : test_operators.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_negate_operator_label(self):
orig_expr = or_(
self.table1.c.myid == 1, self.table1.c.myid == 2
).label("foo")
expr = not_(orig_expr)
isinstance(expr, Label)
eq_(expr.name, "foo")
is_not(expr, orig_expr)
is_(expr._element.operator, operator.inv) # e.g. and not false_
self.assert_compile(
expr,
"NOT (mytable.myid = :myid_1 OR mytable.myid = :myid_2)",
dialect=default.DefaultDialect(supports_native_boolean=False),
)
def test_negate_operator_self_group(self):
3
Source : test_operators.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_negate_operator_self_group(self):
orig_expr = or_(
self.table1.c.myid == 1, self.table1.c.myid == 2
).self_group()
expr = not_(orig_expr)
is_not(expr, orig_expr)
self.assert_compile(
expr,
"NOT (mytable.myid = :myid_1 OR mytable.myid = :myid_2)",
dialect=default.DefaultDialect(supports_native_boolean=False),
)
def test_implicitly_boolean(self):
0
Source : test_events.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_no_instance_level_collections(self):
@event.listens_for(self.Target, "event_one")
def listen_one(x, y):
pass
t1 = self.Target()
t2 = self.Target()
t1.dispatch.event_one(5, 6)
t2.dispatch.event_one(5, 6)
is_(
self.Target.dispatch._empty_listener_reg[self.Target]["event_one"],
t1.dispatch.event_one,
)
@event.listens_for(t1, "event_one")
def listen_two(x, y):
pass
is_not(
self.Target.dispatch._empty_listener_reg[self.Target]["event_one"],
t1.dispatch.event_one,
)
is_(
self.Target.dispatch._empty_listener_reg[self.Target]["event_one"],
t2.dispatch.event_one,
)
def test_exec_once(self):
0
Source : test_types.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_autoincrement(self, metadata, connection, implicit_returning):
Table(
"ai_1",
metadata,
Column("int_y", Integer, primary_key=True, autoincrement=True),
Column("int_n", Integer, DefaultClause("0"), primary_key=True),
implicit_returning=implicit_returning,
)
Table(
"ai_2",
metadata,
Column("int_y", Integer, primary_key=True, autoincrement=True),
Column("int_n", Integer, DefaultClause("0"), primary_key=True),
implicit_returning=implicit_returning,
)
Table(
"ai_3",
metadata,
Column("int_n", Integer, DefaultClause("0"), primary_key=True),
Column("int_y", Integer, primary_key=True, autoincrement=True),
implicit_returning=implicit_returning,
)
Table(
"ai_4",
metadata,
Column("int_n", Integer, DefaultClause("0"), primary_key=True),
Column("int_n2", Integer, DefaultClause("0"), primary_key=True),
implicit_returning=implicit_returning,
)
Table(
"ai_5",
metadata,
Column("int_y", Integer, primary_key=True, autoincrement=True),
Column("int_n", Integer, DefaultClause("0"), primary_key=True),
implicit_returning=implicit_returning,
)
Table(
"ai_6",
metadata,
Column("o1", String(1), DefaultClause("x"), primary_key=True),
Column("int_y", Integer, primary_key=True, autoincrement=True),
implicit_returning=implicit_returning,
)
Table(
"ai_7",
metadata,
Column("o1", String(1), DefaultClause("x"), primary_key=True),
Column("o2", String(1), DefaultClause("x"), primary_key=True),
Column("int_y", Integer, autoincrement=True, primary_key=True),
implicit_returning=implicit_returning,
)
Table(
"ai_8",
metadata,
Column("o1", String(1), DefaultClause("x"), primary_key=True),
Column("o2", String(1), DefaultClause("x"), primary_key=True),
implicit_returning=implicit_returning,
)
metadata.create_all(connection)
table_names = [
"ai_1",
"ai_2",
"ai_3",
"ai_4",
"ai_5",
"ai_6",
"ai_7",
"ai_8",
]
mr = MetaData()
for name in table_names:
tbl = Table(name, mr, autoload_with=connection)
tbl = metadata.tables[name]
# test that the flag itself reflects appropriately
for col in tbl.c:
if "int_y" in col.name:
is_(col.autoincrement, True)
is_(tbl._autoincrement_column, col)
else:
eq_(col.autoincrement, "auto")
is_not(tbl._autoincrement_column, col)
connection.execute(tbl.insert())
if "int_y" in tbl.c:
eq_(
connection.execute(select(tbl.c.int_y)).scalar(),
1,
)
assert (
list(connection.execute(tbl.select()).first()).count(1)
== 1
)
else:
assert 1 not in list(connection.execute(tbl.select()).first())
class StringTest(fixtures.TestBase, AssertsCompiledSQL):
0
Source : test_all.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_all_import(self):
for package in self._all_dialect_packages():
for item_name in package.__all__:
is_not(None, getattr(package, item_name))
0
Source : test_execute.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_execution_options_modify_inplace(self):
engine = engines.testing_engine()
@event.listens_for(engine, "set_engine_execution_options")
def engine_tracker(conn, opt):
opt["engine_tracked"] = True
@event.listens_for(engine, "set_connection_execution_options")
def conn_tracker(conn, opt):
opt["conn_tracked"] = True
with mock.patch.object(
engine.dialect, "set_connection_execution_options"
) as conn_opt, mock.patch.object(
engine.dialect, "set_engine_execution_options"
) as engine_opt:
e2 = engine.execution_options(e1="opt_e1")
c1 = engine.connect()
c2 = c1.execution_options(c1="opt_c1")
is_not(e2, engine)
is_(c1, c2)
eq_(e2._execution_options, {"e1": "opt_e1", "engine_tracked": True})
eq_(c2._execution_options, {"c1": "opt_c1", "conn_tracked": True})
eq_(
engine_opt.mock_calls,
[mock.call(e2, {"e1": "opt_e1", "engine_tracked": True})],
)
eq_(
conn_opt.mock_calls,
[mock.call(c1, {"c1": "opt_c1", "conn_tracked": True})],
)
@testing.requires.sequences
0
Source : test_execute.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def _test_alter_invalidate_pool_to_false(self, set_to_false):
orig_error = True
engine = engines.testing_engine()
@event.listens_for(engine, "handle_error")
def evt(ctx):
if set_to_false:
ctx.invalidate_pool_on_disconnect = False
c1, c2, c3 = (
engine.pool.connect(),
engine.pool.connect(),
engine.pool.connect(),
)
crecs = [conn._connection_record for conn in (c1, c2, c3)]
c1.close()
c2.close()
c3.close()
with patch.object(
engine.dialect, "is_disconnect", Mock(return_value=orig_error)
):
with engine.connect() as c:
target_crec = c.connection._connection_record
try:
c.exec_driver_sql("SELECT x FROM nonexistent")
assert False
except tsa.exc.StatementError as st:
eq_(st.connection_invalidated, True)
for crec in crecs:
if crec is target_crec or not set_to_false:
is_not(crec.dbapi_connection, crec.get_connection())
else:
is_(crec.dbapi_connection, crec.get_connection())
def test_alter_invalidate_pool_to_false(self):
0
Source : test_execute.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_dont_create_transaction_on_initialize(self):
"""test that engine init doesn't invoke autobegin.
this happened implicitly in 1.4 due to use of a non-future
connection for initialize.
to fix for 2.0 we added a new flag _allow_autobegin=False
for init purposes only.
"""
e = create_engine("sqlite://")
init_connection = None
def mock_initialize(connection):
# definitely trigger what would normally be an autobegin
connection.execute(select(1))
nonlocal init_connection
init_connection = connection
with mock.patch.object(
e._connection_cls, "begin"
) as mock_begin, mock.patch.object(
e.dialect, "initialize", Mock(side_effect=mock_initialize)
) as mock_init:
conn = e.connect()
eq_(mock_begin.mock_calls, [])
is_not(init_connection, None)
is_not(conn, init_connection)
is_false(init_connection._allow_autobegin)
eq_(mock_init.mock_calls, [mock.call(init_connection)])
# assert the mock works too
conn.begin()
eq_(mock_begin.mock_calls, [mock.call()])
conn.close()
def test_invalidate_on_connect(self):
0
Source : test_execute.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_initialize_connect_calls(self):
"""test for :ticket:`5497`, on_connect not called twice"""
m1 = Mock()
cls_ = testing.db.dialect.__class__
class SomeDialect(cls_):
def initialize(self, connection):
super(SomeDialect, self).initialize(connection)
m1.initialize(connection)
def on_connect(self):
oc = super(SomeDialect, self).on_connect()
def my_on_connect(conn):
if oc:
oc(conn)
m1.on_connect(conn)
return my_on_connect
u1 = Mock(
username=None,
password=None,
host=None,
port=None,
query={},
database=None,
_instantiate_plugins=lambda kw: (u1, [], kw),
_get_entrypoint=Mock(
return_value=Mock(get_dialect_cls=lambda u: SomeDialect)
),
)
eng = create_engine(u1, poolclass=QueuePool)
# make sure other dialects aren't getting pulled in here
eq_(eng.name, "sqlite")
c = eng.connect()
dbapi_conn_one = c.connection.dbapi_connection
c.close()
eq_(
m1.mock_calls,
[call.on_connect(dbapi_conn_one), call.initialize(mock.ANY)],
)
c = eng.connect()
eq_(
m1.mock_calls,
[call.on_connect(dbapi_conn_one), call.initialize(mock.ANY)],
)
c2 = eng.connect()
dbapi_conn_two = c2.connection.dbapi_connection
is_not(dbapi_conn_one, dbapi_conn_two)
eq_(
m1.mock_calls,
[
call.on_connect(dbapi_conn_one),
call.initialize(mock.ANY),
call.on_connect(dbapi_conn_two),
],
)
c.close()
c2.close()
@testing.only_on("sqlite+pysqlite")
0
Source : test_pool.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_info(self):
p = self._queuepool_fixture(pool_size=1, max_overflow=0)
c = p.connect()
self.assert_(not c.info)
self.assert_(c.info is c._connection_record.info)
c.info["foo"] = "bar"
c.close()
del c
c = p.connect()
self.assert_("foo" in c.info)
c.invalidate()
c = p.connect()
self.assert_("foo" not in c.info)
c.info["foo2"] = "bar2"
c.detach()
self.assert_("foo2" in c.info)
c2 = p.connect()
is_not(c.dbapi_connection, c2.dbapi_connection)
assert not c2.info
assert "foo2" in c.info
def test_rec_info(self):
0
Source : test_pool.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_rec_close_reopen(self):
# test that _ConnectionRecord.close() allows
# the record to be reusable
dbapi = MockDBAPI()
p1 = pool.Pool(creator=lambda: dbapi.connect("foo.db"))
r1 = pool._ConnectionRecord(p1)
c1 = r1.dbapi_connection
c2 = r1.get_connection()
is_(c1, c2)
r1.close()
assert not r1.dbapi_connection
eq_(c1.mock_calls, [call.close()])
c2 = r1.get_connection()
is_not(c1, c2)
is_(c2, r1.dbapi_connection)
eq_(c2.mock_calls, [])
@testing.combinations(
0
Source : test_pool.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_recycle(self):
with patch("sqlalchemy.pool.base.time.time") as mock:
mock.return_value = 10000
p = self._queuepool_fixture(
pool_size=1, max_overflow=0, recycle=30
)
c1 = p.connect()
c_ref = weakref.ref(c1.dbapi_connection)
c1.close()
mock.return_value = 10001
c2 = p.connect()
is_(c2.dbapi_connection, c_ref())
c2.close()
mock.return_value = 10035
c3 = p.connect()
is_not(c3.dbapi_connection, c_ref())
@testing.requires.timing_intensive
0
Source : test_pool.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_recycle_on_soft_invalidate(self):
p = self._queuepool_fixture(pool_size=1, max_overflow=0)
c1 = p.connect()
c_ref = weakref.ref(c1.dbapi_connection)
c1.close()
c2 = p.connect()
is_(c2.dbapi_connection, c_ref())
c2_rec = c2._connection_record
# ensure pool invalidate time will be later than starttime
# for ConnectionRecord objects above
time.sleep(0.1)
c2.invalidate(soft=True)
is_(c2_rec.dbapi_connection, c2.dbapi_connection)
c2.close()
c3 = p.connect()
is_not(c3.dbapi_connection, c_ref())
is_(c3._connection_record, c2_rec)
is_(c2_rec.dbapi_connection, c3.dbapi_connection)
def _no_wr_finalize(self):
0
Source : test_engine_py3k.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
async def test_invalidate(self, async_engine):
conn = await async_engine.connect()
is_(conn.invalidated, False)
connection_fairy = await conn.get_raw_connection()
is_(connection_fairy.is_valid, True)
dbapi_connection = connection_fairy.dbapi_connection
await conn.invalidate()
if testing.against("postgresql+asyncpg"):
assert dbapi_connection._connection.is_closed()
new_fairy = await conn.get_raw_connection()
is_not(new_fairy.dbapi_connection, dbapi_connection)
is_not(new_fairy, connection_fairy)
is_(new_fairy.is_valid, True)
is_(connection_fairy.is_valid, False)
await conn.close()
@async_test
0
Source : test_baked.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_chained_add_operator(self):
User = self.classes.User
session = fixture_session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
q2 = q1 + l2
is_not(q2, q1)
self._assert_cache_key(q1._cache_key, [l1])
self._assert_cache_key(q2._cache_key, [l1, l2])
class LikeQueryTest(BakedTest):
0
Source : test_extendedattr.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_unregister(self, registry):
class MyClassState(instrumentation.InstrumentationManager):
def manage(self, class_, manager):
setattr(class_, "xyz", manager)
def unregister(self, class_, manager):
delattr(class_, "xyz")
def manager_getter(self, class_):
def get(cls):
return cls.xyz
return get
class MyClass:
__sa_instrumentation_manager__ = MyClassState
assert attributes.manager_of_class(MyClass) is None
t = Table(
"my_table",
registry.metadata,
Column("id", Integer, primary_key=True),
)
registry.map_imperatively(MyClass, t)
manager = attributes.manager_of_class(MyClass)
is_not(manager, None)
is_(manager, MyClass.xyz)
registry.configure()
registry.dispose()
manager = attributes.manager_of_class(MyClass)
is_(manager, None)
assert not hasattr(MyClass, "xyz")
class UserDefinedExtensionTest(_ExtBase, fixtures.ORMTest):
0
Source : test_attributes.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_loader_inits_collection_already_exists(self):
A, B = self.A, self.B
a1 = A()
b1, b2 = B(), B()
a1.bs = [b1, b2]
eq_(a1.__dict__["bs"], [b1, b2])
old = a1.__dict__["bs"]
is_not(old._sa_adapter, None)
state = attributes.instance_state(a1)
# this occurs during a load with populate_existing
adapter = attributes.init_state_collection(state, state.dict, "bs")
new = a1.__dict__["bs"]
eq_(new, [])
is_(new._sa_adapter, adapter)
is_(old._sa_adapter, None)
class TestUnlink(fixtures.TestBase):
0
Source : test_eager_relations.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_many_to_one(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties=dict(
user=relationship(
self.mapper_registry.map_imperatively(User, users),
lazy="joined",
)
),
)
sess = fixture_session()
q = sess.query(Address)
def go():
a = q.filter(addresses.c.id == 1).one()
is_not(a.user, None)
u1 = sess.get(User, 7)
is_(a.user, u1)
self.assert_sql_count(testing.db, go, 1)
def test_many_to_one_null(self):
0
Source : test_events.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_pending_to_persistent_del(self):
sess, User, start_events = self._fixture()
@event.listens_for(sess, "pending_to_persistent")
def pending_to_persistent(session, instance):
listener.flag_checked(instance)
# this is actually u1, because
# we have a strong ref internally
is_not(None, instance)
u1 = User(name="u1")
sess.add(u1)
u1_inst_state = u1._sa_instance_state
del u1
gc_collect()
listener = start_events()
sess.flush()
eq_(
listener.mock_calls,
[
call.flag_checked(u1_inst_state.obj()),
call.pending_to_persistent(sess, u1_inst_state.obj()),
],
)
def test_persistent_to_deleted_del(self):
0
Source : test_events.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_persistent_to_deleted_del(self):
sess, User, start_events = self._fixture()
u1 = User(name="u1")
sess.add(u1)
sess.flush()
listener = start_events()
@event.listens_for(sess, "persistent_to_deleted")
def persistent_to_deleted(session, instance):
is_not(None, instance)
listener.flag_checked(instance)
sess.delete(u1)
u1_inst_state = u1._sa_instance_state
del u1
gc_collect()
sess.flush()
eq_(
listener.mock_calls,
[
call.persistent_to_deleted(sess, u1_inst_state.obj()),
call.flag_checked(u1_inst_state.obj()),
],
)
def test_detached_to_persistent(self):
0
Source : test_selectin_relations.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_many_to_one(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties=dict(
user=relationship(
self.mapper_registry.map_imperatively(User, users),
lazy="selectin",
)
),
)
sess = fixture_session()
q = sess.query(Address)
def go():
a = q.filter(addresses.c.id == 1).one()
is_not(a.user, None)
u1 = sess.get(User, 7)
is_(a.user, u1)
self.assert_sql_count(testing.db, go, 2)
def test_m2o_none_value_present(self):
0
Source : test_session.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_autobegin_execute(self):
# test the new autobegin behavior introduced in #5074
s = Session(testing.db)
is_(s._transaction, None)
s.execute(select(1))
is_not(s._transaction, None)
s.commit()
is_(s._transaction, None)
s.execute(select(1))
is_not(s._transaction, None)
s.close()
is_(s._transaction, None)
s.execute(select(1))
is_not(s._transaction, None)
s.close()
is_(s._transaction, None)
def test_autobegin_flush(self):
0
Source : test_session.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_autobegin_flush(self):
# test the new autobegin behavior introduced in #5074
User, users = self.classes.User, self.tables.users
self.mapper_registry.map_imperatively(User, users)
s = Session(testing.db)
is_(s._transaction, None)
# empty flush, nothing happens
s.flush()
is_(s._transaction, None)
s.add(User(id=1, name="name"))
s.flush()
is_not(s._transaction, None)
s.commit()
is_(s._transaction, None)
def test_autobegin_within_flush(self):
0
Source : test_subquery_relations.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_many_to_one(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties=dict(
user=relationship(
self.mapper_registry.map_imperatively(User, users),
lazy="subquery",
)
),
)
sess = fixture_session()
q = sess.query(Address)
def go():
a = q.filter(addresses.c.id == 1).one()
is_not(a.user, None)
u1 = sess.get(User, 7)
is_(a.user, u1)
self.assert_sql_count(testing.db, go, 2)
def test_double_with_aggregate(self):
0
Source : test_transaction.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_failed_rollback_deactivates_transaction(self):
# test #4050
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
session = Session(bind=testing.db)
rollback_error = testing.db.dialect.dbapi.InterfaceError(
"Can't roll back to savepoint"
)
def prevent_savepoint_rollback(
cursor, statement, parameters, context=None
):
if (
context is not None
and context.compiled
and isinstance(
context.compiled.statement,
elements.RollbackToSavepointClause,
)
):
raise rollback_error
self.event_listen(
testing.db.dialect, "do_execute", prevent_savepoint_rollback
)
with session.begin():
session.add(User(id=1, name="x"))
session.begin_nested()
# raises IntegrityError on flush
session.add(User(id=1, name="x"))
assert_raises_message(
sa_exc.InterfaceError,
"Can't roll back to savepoint",
session.commit,
)
# rollback succeeds, because the Session is deactivated
eq_(session._transaction._state, _session.DEACTIVE)
eq_(session.is_active, False)
session.rollback()
is_(session._transaction, None)
session.connection()
# back to normal
eq_(session._transaction._state, _session.ACTIVE)
eq_(session.is_active, True)
trans = session._transaction
# leave the outermost trans
session.rollback()
# trans is now closed
eq_(trans._state, _session.CLOSED)
# outermost transaction is new
is_not(session._transaction, trans)
is_(session._transaction, None)
eq_(session.is_active, True)
def test_no_prepare_wo_twophase(self):
0
Source : test_transaction.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_savepoint_lost_still_runs(self):
User = self.classes.User
s = fixture_session()
trans = s.begin_nested()
s.connection()
u1 = User(name="ed")
s.add(u1)
# kill off the transaction
nested_trans = trans._connections[self.bind][1]
nested_trans._do_commit()
is_(s.get_nested_transaction(), trans)
with expect_warnings("nested transaction already deassociated"):
# this previously would raise
# "savepoint "sa_savepoint_1" does not exist", however as of
# #5327 the savepoint already knows it's inactive
s.rollback()
assert u1 not in s.new
is_(trans._state, _session.CLOSED)
is_not(s.get_transaction(), trans)
s.connection()
is_(s.get_transaction()._state, _session.ACTIVE)
is_(s.get_transaction().nested, False)
is_(s.get_transaction()._parent, None)
class AccountingFlagsTest(_LocalFixture):
0
Source : test_transaction.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_session_as_ctx_manager_one(self):
users = self.tables.users
with fixture_session() as sess:
is_(sess.get_transaction(), None)
sess.connection().execute(
users.insert().values(id=1, name="user1")
)
eq_(
sess.connection().execute(users.select()).all(), [(1, "user1")]
)
is_not(sess.get_transaction(), None)
is_(sess.get_transaction(), None)
# did not commit
eq_(sess.connection().execute(users.select()).all(), [])
def test_session_as_ctx_manager_two(self):
0
Source : test_compare.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_generative_cache_key_regen_w_del(self):
t1 = table("t1", column("a"), column("b"))
s1 = select(t1)
ck1 = s1._generate_cache_key()
s2 = s1.where(t1.c.a == 5)
del s1
# there is now a good chance that id(s3) == id(s1), make sure
# cache key is regenerated
s3 = s2.order_by(t1.c.b)
ck3 = s3._generate_cache_key()
ne_(ck1, ck3)
is_not(ck1, None)
is_not(ck3, None)
class CompareAndCopyTest(CoreFixtures, fixtures.TestBase):
0
Source : test_computed.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_to_metadata(self):
comp1 = Computed("x + 2")
m = MetaData()
t = Table("t", m, Column("x", Integer), Column("y", Integer, comp1))
is_(comp1.column, t.c.y)
is_(t.c.y.server_onupdate, comp1)
is_(t.c.y.server_default, comp1)
m2 = MetaData()
t2 = t.to_metadata(m2)
comp2 = t2.c.y.server_default
is_not(comp1, comp2)
is_(comp1.column, t.c.y)
is_(t.c.y.server_onupdate, comp1)
is_(t.c.y.server_default, comp1)
is_(comp2.column, t2.c.y)
is_(t2.c.y.server_onupdate, comp2)
is_(t2.c.y.server_default, comp2)
0
Source : test_external_traversal.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_labeled_expression_adapt(self):
lbl_x = (t3.c.col1 == 1).label("x")
t3_alias = t3.alias()
adapter = sql_util.ColumnAdapter(t3_alias)
lblx_adapted = adapter.traverse(lbl_x)
is_not(lblx_adapted._element, lbl_x._element)
lblx_adapted = adapter.traverse(lbl_x)
self.assert_compile(
select(lblx_adapted.self_group()),
"SELECT (table3_1.col1 = :col1_1) AS x FROM table3 AS table3_1",
)
self.assert_compile(
select(lblx_adapted.is_(True)),
"SELECT (table3_1.col1 = :col1_1) IS 1 AS anon_1 "
"FROM table3 AS table3_1",
)
def test_cte_w_union(self):
0
Source : test_external_traversal.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_wrapping_ordering(self):
"""illustrate an example where order of wrappers matters.
This test illustrates both the ordering being significant
as well as a scenario where multiple translations are needed
(e.g. wrapping vs. chaining).
"""
stmt = (
select(t1.c.col1, t2.c.col1)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
sa = stmt.alias()
stmt2 = select(t2, sa).subquery()
a1 = sql_util.ColumnAdapter(stmt)
a2 = sql_util.ColumnAdapter(stmt2)
a2_to_a1 = a2.wrap(a1)
a1_to_a2 = a1.wrap(a2)
# when stmt2 and stmt represent the same column
# in different contexts, order of wrapping matters
# t2.c.col1 via a2 is stmt2.c.col1; then ignored by a1
is_(a2_to_a1.columns[t2.c.col1], stmt2.c.col1)
# t2.c.col1 via a1 is stmt.c.table2_col1; a2 then
# sends this to stmt2.c.table2_col1
is_(a1_to_a2.columns[t2.c.col1], stmt2.c.table2_col1)
# check that these aren't the same column
is_not(stmt2.c.col1, stmt2.c.table2_col1)
# for mutually exclusive columns, order doesn't matter
is_(a2_to_a1.columns[t1.c.col1], stmt2.c.table1_col1)
is_(a1_to_a2.columns[t1.c.col1], stmt2.c.table1_col1)
is_(a2_to_a1.columns[t2.c.col2], stmt2.c.col2)
def test_wrapping_multiple(self):
0
Source : test_selectable.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_deannotate_wrapping(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})
b3 = sql_util._deep_deannotate(b2)
b4 = sql_util._deep_deannotate(bin_)
for elem in (b2._annotations, b2.left._annotations):
in_("_orm_adapt", elem)
for elem in (
b3._annotations,
b3.left._annotations,
b4._annotations,
b4.left._annotations,
):
eq_(elem, {})
is_not(b2.left, bin_.left)
is_not(b3.left, b2.left)
is_not(b2.left, bin_.left)
is_(b4.left, bin_.left) # since column is immutable
# deannotate copies the element
is_not(bin_.right, b2.right)
is_not(b2.right, b3.right)
is_not(b3.right, b4.right)
def test_deannotate_clone(self):
0
Source : test_selectable.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_deannotate_clone(self):
table1 = table("table1", column("col1"), column("col2"))
subq = (
select(table1).where(table1.c.col1 == bindparam("foo")).subquery()
)
stmt = select(subq)
s2 = sql_util._deep_annotate(stmt, {"_orm_adapt": True})
s3 = sql_util._deep_deannotate(s2)
s4 = sql_util._deep_deannotate(s3)
eq_(stmt._annotations, {})
eq_(subq._annotations, {})
eq_(s2._annotations, {"_orm_adapt": True})
eq_(s3._annotations, {})
eq_(s4._annotations, {})
# select._raw_columns[0] is the subq object
eq_(s2._raw_columns[0]._annotations, {"_orm_adapt": True})
eq_(s3._raw_columns[0]._annotations, {})
eq_(s4._raw_columns[0]._annotations, {})
is_not(s3, s2)
is_not(s4, s3) # deep deannotate makes a clone unconditionally
is_(s3._deannotate(), s3) # regular deannotate returns same object
def test_annotate_unique_traversal(self):
0
Source : test_types.py
with MIT License
from sqlalchemy
with MIT License
from sqlalchemy
def test_variant_righthand_coercion_honors_wrapped(self):
my_json_normal = JSON()
my_json_variant = JSON().with_variant(String(), "sqlite")
tab = table(
"test",
column("avalue", my_json_normal),
column("bvalue", my_json_variant),
)
expr = tab.c.avalue["foo"] == "bar"
is_(expr.right.type._type_affinity, String)
is_not(expr.right.type, my_json_normal)
expr = tab.c.bvalue["foo"] == "bar"
is_(expr.right.type._type_affinity, String)
is_not(expr.right.type, my_json_variant)
def test_variant_righthand_coercion_returns_self(self):