async def test_no_async_listeners_pool_event(self, async_engine): with testing.expect_raises_message( NotImplementedError, "asynchronous events are not implemented " "at this time. Apply synchronous listeners to the " "AsyncEngine.sync_engine or " "AsyncConnection.sync_connection attributes.", ): event.listen(async_engine, "checkout", mock.Mock())
def thread_go(q): def go(): eq_(q.get(block=False), 1) q.get(timeout=0.1) with expect_raises_message(RuntimeError, ".* to a different .*loop"): asyncio.run(greenlet_spawn(go)) run[0] = True
async def test_await_only_no_greenlet(self): to_await = run1() with expect_raises_message( exc.MissingGreenlet, r"greenlet_spawn has not been called; can't call await_\(\) here.", ): await_only(to_await) # ensure no warning await greenlet_spawn(await_fallback, to_await)
async def test_no_async_listeners(self, async_engine): with testing.expect_raises_message( NotImplementedError, "asynchronous events are not implemented " "at this time. Apply synchronous listeners to the " "AsyncEngine.sync_engine or " "AsyncConnection.sync_connection attributes.", ): event.listen(async_engine, "before_cursor_execute", mock.Mock()) async with async_engine.connect() as conn: with testing.expect_raises_message( NotImplementedError, "asynchronous events are not implemented " "at this time. Apply synchronous listeners to the " "AsyncEngine.sync_engine or " "AsyncConnection.sync_connection attributes.", ): event.listen(conn, "before_cursor_execute", mock.Mock())
async def test_one_no_result(self, async_engine): users = self.tables.users async with async_engine.connect() as conn: result = await conn.stream( select(users).where(users.c.user_name == "nonexistent")) with expect_raises_message( exc.NoResultFound, "No row was found when one was required"): await result.one()
async def test_conn_transaction_not_started(self, async_engine): async with async_engine.connect() as conn: trans = conn.begin() with expect_raises_message( asyncio_exc.AsyncContextNotStarted, "AsyncTransaction context has not been started " "and object has not been awaited.", ): await trans.rollback(),
def test_await_only_no_greenlet(self): to_await = run1() with expect_raises_message( exc.InvalidRequestError, r"greenlet_spawn has not been called; can't call await_\(\) here.", ): await_only(to_await) # ensure no warning await_fallback(to_await)
async def test_get_dbapi_connection_raise(self, async_engine): conn = await async_engine.connect() with testing.expect_raises_message( exc.InvalidRequestError, "AsyncConnection.connection accessor is not " "implemented as the attribute", ): conn.connection
def test_VARBINARY_init(self): d = mssql.dialect() t = mssql.MSVarBinary(length=None, filestream=True) eq_(str(t.compile(dialect=d)), "VARBINARY(max) FILESTREAM") t = mssql.MSVarBinary(length="max", filestream=True) eq_(str(t.compile(dialect=d)), "VARBINARY(max) FILESTREAM") with expect_raises_message( ValueError, "length must be None or 'max' when setting filestream"): mssql.MSVarBinary(length=1000, filestream=True)
async def test_closed_during_execute(self, metadata, async_testing_engine): engine = async_testing_engine() async with engine.connect() as conn: await conn.begin() with testing.expect_raises_message(exc.DBAPIError, "connection was closed"): await conn.exec_driver_sql( "select pg_terminate_backend(pg_backend_pid())")
async def test_one_multi_result(self, async_engine): users = self.tables.users async with async_engine.connect() as conn: result = await conn.stream( select(users).where(users.c.user_name.in_(["name3", "name5"]))) with expect_raises_message( exc.MultipleResultsFound, "Multiple rows were found when exactly one was required", ): await result.one()
async def test_no_ss_cursor_w_exec_driver_sql(self, async_engine): async with async_engine.connect() as conn: conn = await conn.execution_options(stream_results=True) with expect_raises_message( async_exc.AsyncMethodRequired, r"Can't use the AsyncConnection.exec_driver_sql\(\) " r"method with a " r"server-side cursor. Use the AsyncConnection.stream\(\) " r"method for an async streaming result set.", ): await conn.exec_driver_sql("SELECT * FROM users")
def test_no_decimal_float_precision(self): with expect_raises_message( exc.ArgumentError, "Oracle FLOAT types use 'binary precision', which does not " "convert cleanly from decimal 'precision'. Please specify this " "type with a separate Oracle variant, such as " r"FLOAT\(precision=5\).with_variant\(oracle.FLOAT\(" r"binary_precision=16\), 'oracle'\), so that the Oracle " "specific 'binary_precision' may be specified accurately.", ): FLOAT(5).compile(dialect=oracle.dialect())
async def test_require_await(self): def run(): return 1 + 1 assert (await greenlet_spawn(run)) == 2 with expect_raises_message( exc.AwaitRequired, "The current operation required an async execution but none was", ): await greenlet_spawn(run, _require_await=True)
async def test_no_ss_cursor_w_execute(self, async_engine): users = self.tables.users async with async_engine.connect() as conn: conn = await conn.execution_options(stream_results=True) with expect_raises_message( async_exc.AsyncMethodRequired, r"Can't use the AsyncConnection.execute\(\) method with a " r"server-side cursor. Use the AsyncConnection.stream\(\) " r"method for an async streaming result set.", ): await conn.execute(select(users))
def test_use_cols_tricky_not_every_type_given( self, tricky_types_parameter_fixture): literal_parameter_fixture = tricky_types_parameter_fixture(True, omit=(1, )) stmt = select(literal_parameter_fixture) with expect_raises_message( exc.CompileError, "Don't know how to render literal SQL value: 'textA'", ): str(stmt)
def test_no_recursion_depth_non_self_referential(self, loader): User = self.classes.User sess = fixture_session() stmt = select(User).options( selectinload(User.addresses, recursion_depth=-1)) with expect_raises_message( sa.exc.InvalidRequestError, "recursion_depth option on relationship User.addresses not valid", ): sess.execute(stmt).all()
def test_wrong_number_of_elements(self): v1 = Values( column("CaseSensitive", Integer), column("has spaces", String), name="Spaces and Cases", ).data([(1, "textA", 99), (2, "textB", 88)]) with expect_raises_message( exc.ArgumentError, r"Wrong number of elements for 2-tuple: \(1, 'textA', 99\)", ): str(v1)
def test_distill_20_sequence_error(self): with expect_raises_message( exc.ArgumentError, "List argument must consist only of tuples or dictionaries", ): self.module._distill_params_20((1, 2, 3)) with expect_raises_message( exc.ArgumentError, "List argument must consist only of tuples or dictionaries", ): self.module._distill_params_20(([1, 2, 3],)) with expect_raises_message( exc.ArgumentError, "List argument must consist only of tuples or dictionaries", ): self.module._distill_params_20([1, 2, 3]) with expect_raises_message( exc.ArgumentError, "List argument must consist only of tuples or dictionaries", ): self.module._distill_params_20(["a", "b"])
def test_expression_isnt_clause_element(self): A = self._wrong_expr_fixture() from sqlalchemy.sql import coercions, roles with testing.expect_raises_message( exc.InvalidRequestError, 'When interpreting attribute "A.value" as a SQL expression, ' r"expected __clause_element__\(\) to return a " "ClauseElement object, got: True", ): coercions.expect(roles.ExpressionElementRole, A.value)
def test_missing_mapped_lhs(self, decl_base): with expect_raises_message( ArgumentError, r'Type annotation for "User.name" should use the ' r'syntax "Mapped\[str\]" or "MappedColumn\[str\]"', ): class User(decl_base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) name: str = mapped_column() # type: ignore
def test_incompatible_options_add_instancelevel(self): class opt1(sql_base.CacheableOptions): _cache_key_traversal = [] foo = "bar" o1 = opt1(foo="bat") with expect_raises_message( TypeError, "dictionary contains attributes not covered by " "Options class .*opt1.* .*'bar'.*", ): o1 += {"foo": "f", "bar": "b"}
def test_other_programming_error_on_rollback(self): """test #8231""" class ProgrammingError(Exception): pass dialect = base.dialect(ignore_no_transaction_on_rollback=True) dialect.dbapi = mock.Mock(ProgrammingError=ProgrammingError) connection = mock.Mock(rollback=mock.Mock( side_effect=ProgrammingError("Some other error happened"))) with expect_raises_message(ProgrammingError, "Some other error happened"): dialect.do_rollback(connection)
def test_wrong_annotation_type_one(self, decl_base): with expect_raises_message( sa_exc.ArgumentError, r"Type annotation for \"A.data\" should use the " r"syntax \"Mapped\['B'\]\" or \"Relationship\['B'\]\"", ): class A(decl_base): __tablename__ = "a" id: Mapped[int] = mapped_column(primary_key=True) data: "B" = relationship() # type: ignore # noqa
def test_required_no_arg(self, decl_base): with expect_raises_message( sa_exc.ArgumentError, r"Python typing annotation is required for attribute " r'"A.data" when primary ' r'argument\(s\) for "MappedColumn" construct are None or ' r"not present", ): class A(decl_base): __tablename__ = "a" id: Mapped[int] = mapped_column(primary_key=True) data = mapped_column()
def test_construct_lhs_type_missing(self, decl_base): class MyClass: pass with expect_raises_message( sa_exc.ArgumentError, "Could not locate SQLAlchemy Core type for Python type: .*MyClass", ): class User(decl_base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[MyClass] = mapped_column()
def test_dc_raise_for_slots( self, registry: _RegistryType, decl_base: Type[DeclarativeBase], ): reg = registry with expect_raises_message( exc.ArgumentError, r"Dataclass argument\(s\) 'slots', 'unknown' are not accepted", ): class A(MappedAsDataclass, decl_base): __tablename__ = "a" _sa_apply_dc_transforms = {"slots": True, "unknown": 5} id: Mapped[int] = mapped_column(primary_key=True, init=False) with expect_raises_message( exc.ArgumentError, r"Dataclass argument\(s\) 'slots' are not accepted", ): class Base(MappedAsDataclass, DeclarativeBase, order=True): registry = reg _sa_apply_dc_transforms = {"slots": True} with expect_raises_message( exc.ArgumentError, r"Dataclass argument\(s\) 'slots', 'unknown' are not accepted", ): @reg.mapped class C: __tablename__ = "a" _sa_apply_dc_transforms = {"slots": True, "unknown": 5} id: Mapped[int] = mapped_column(primary_key=True, init=False)
def test_no_field_args_w_new_style(self, registry: _RegistryType): with expect_raises_message( exc.InvalidRequestError, "SQLAlchemy mapped dataclasses can't consume mapping information", ): @registry.mapped_as_dataclass() class A: __tablename__ = "a" __sa_dataclass_metadata_key__ = "sa" account_id: int = dataclasses.field( init=False, metadata={"sa": Column(Integer, primary_key=True)}, )
def test_no_call_twice(self): stmt = insert(self.table).values( [{"id": 1, "bar": "ab"}, {"id": 2, "bar": "b"}] ) stmt = stmt.on_duplicate_key_update( bar=stmt.inserted.bar, baz=stmt.inserted.baz ) with testing.expect_raises_message( exc.InvalidRequestError, "This Insert construct already has an " "ON DUPLICATE KEY clause present", ): stmt = stmt.on_duplicate_key_update( bar=stmt.inserted.bar, baz=stmt.inserted.baz )
def test_raise_on_regular_python_obj_for_expr(self): """test #6350""" def some_function(): pass class Thing(object): def __clause_element__(self): return some_function with testing.expect_raises_message( exc.ArgumentError, r"SQL expression element expected, got " "<function .*some_function .* resolved from <.*Thing object .*", ): expect(roles.ExpressionElementRole, Thing())