def test_database_session__returns_new_session_object(db: Database): session = db.session() assert isinstance(session, Session) assert not session.in_transaction() other_session = db.session() assert other_session is not session
def test_database_ping__raises_exception_on_failure(db: Database): mocked_scalar = mock.Mock(side_effect=DBAPIError(None, None, None)) mocked_engine = create_engine_mock(scalar=mocked_scalar) with mock_db(db, engine=mocked_engine): with pytest.raises(DBAPIError): db.ping()
def test_database_begin__starts_new_transaction(db: Database): with db.begin() as session: assert isinstance(session, Session) assert session.in_transaction() with db.begin() as other_session: assert other_session is not session
def test_session_save__does_not_commit(db: Database): with db.session() as session: session.save(User()) with db.session() as session: select_count = sa.select(sa.func.count(User.id)) assert session.one(select_count) == 0
def test_database_ping__raises_when_invalidated_connection_retry_fails( db: Database): mocked_scalar = mock.Mock( side_effect=DBAPIError(None, None, None, connection_invalidated=True)) mocked_engine = create_engine_mock(scalar=mocked_scalar) with mock_db(db, engine=mocked_engine): with pytest.raises(DBAPIError): db.ping()
def test_session_save_all__returns_list(db: Database): users = [User(), User(), User()] with db.begin() as session: result = session.save_all(users) assert isinstance(result, list) assert result == users with db.session() as session: select_count = sa.select(sa.func.count(User.id)) assert session.one(select_count) == len(users)
def test_session_save_all__accepts_single_model_and_returns_list(db: Database): user = User() with db.begin() as session: result = session.save_all(user) assert isinstance(result, list) assert result == [user] with db.session() as session: select_count = sa.select(sa.func.count(User.id)) assert session.one(select_count) == 1
def test_session_save__inserts_new_without_pk(db: Database): user = User(name="n") with db.begin() as session: session.save(user) assert user.id == 1 assert user.name == "n" with db.session() as session: select_count = sa.select(sa.func.count(User.id)) assert session.one(select_count) == 1
def test_model_to_dict__loaded_from_database(db: Database, model: ModelBase, args: dict, load_options: list, expected: dict): with db.begin() as session: session.add(model) with db.session() as session: fetched_model = session.first( type(model).select().options(*load_options)) assert fetched_model is not None assert fetched_model.to_dict(**args) == expected
def test_session_save__updates_existing_in_same_session(db: Database): with db.session() as session: user = User(id=1) session.add(user) session.commit() user.name = "n" session.save(user) session.commit() with db.session() as session: select_count = sa.select(sa.func.count(User.id)) assert session.one(select_count) == 1
def test_database_session__can_override_default_options( db: Database, option, default_value, override_value): session = db.session() option_value = getattr(session, option) assert ( option_value == default_value ), f"Expected session.{option} to be {default_value!r}, not {option_value!r}" session = db.session(**{option: override_value}) option_value = getattr(session, option) assert ( option_value == override_value ), f"Expected session.{option} to be {override_value!r}, not {option_value!r}"
def test_database_create_all(): model_collection = create_model_collection() model_class = model_collection["model_class"] model_tables = model_collection["tables"] db = Database("sqlite://", model_class=model_class) db.create_all() with db.connect() as conn: result = conn.execute(sa.text("SELECT name FROM sqlite_master")) table_names = result.scalars().all() assert len(table_names) == len(model_tables) for table_name in table_names: assert table_name in db.tables
def test_session_save__updates_existing(db: Database): existing_user = create_users(db, count=1)[0] assert existing_user.id == 1 assert existing_user.name is None new_user = User(id=1, name="n") with db.begin() as session: session.save(existing_user) assert new_user.id == 1 assert new_user.name == "n" with db.session() as session: select_count = sa.select(sa.func.count(User.id)) assert session.one(select_count) == 1
def test_database_settings__accepts_engine_options_dict(): engine_options = {"echo": True} other_options = {"encoding": "utf8", "echo": False} expected_options = {**other_options, **engine_options} db = Database("sqlite://", engine_options=engine_options, **other_options) assert db.settings.get_engine_options() == expected_options
def test_session_one__returns_one_model_or_raises(db: Database): users = create_users(db) user = users[0] with db.session() as session: result = session.one(sa.select(User).where(User.id == user.id)) assert isinstance(result, User) assert result.id == user.id with pytest.raises(MultipleResultsFound): with db.session() as session: session.one(sa.select(User)) with pytest.raises(NoResultFound): with db.session() as session: session.one(sa.select(User).where(User.id == 0))
def test_session_save_all__raises_on_duplicate_primary_keys_in_list( db: Database): users = [User(id=1), User(id=1)] with pytest.raises(TypeError): with db.begin() as session: session.save_all(users)
def test_session_all__returns_all_models(db: Database): users = create_users(db) with db.session() as session: results = session.all(sa.select(User)) assert len(results) == len(users) for model in results: assert isinstance(model, User)
def test_database_ping__retries_on_invalidated_connection(filedb: Database): mocked_scalar = mock.Mock(side_effect=[ DBAPIError(None, None, None, connection_invalidated=True), 1 ]) mocked_engine = create_engine_mock(scalar=mocked_scalar) with mock_db(filedb, engine=mocked_engine): assert filedb.ping() is True
def test_session_first__returns_first_result_or_none(db: Database): create_users(db) with db.session() as session: result = session.first(sa.select(User)) assert isinstance(result, User) result = session.first(sa.select(User).where(User.id == 0)) assert result is None
def test_database_settings__accepts_session_options_dict(): session_options = {"autoflush": False} other_options = {"expire_on_commit": True, "autoflush": True} expected_options = {**other_options, **session_options} db = Database("sqlite://", session_options=session_options, **other_options) assert db.settings.get_session_options() == expected_options
def create_users(db: Database, count: int = 3, overrides: t.Optional[dict] = None) -> t.List[User]: if overrides is None: overrides = {} users = [User(id=i, **overrides) for i in range(1, count + 1)] with db.begin(expire_on_commit=False) as session: session.add_all(users) return users
def test_session_all__uniquifies_joinedload_results(db: Database): users = [ User(id=1, addresses=[Address(id=11), Address(id=12), Address(id=13)]), User(id=2, addresses=[Address(id=21), Address(id=22), Address(id=23)]), User(id=3, addresses=[Address(id=31), Address(id=32), Address(id=33)]), ] with db.begin() as session: session.add_all(users) stmt = sa.select(User).options(joinedload(User.addresses)) with db.session() as session: results = session.all(stmt) assert len(results) == len(users)
def test_session_one_or_none__returns_one_row_or_none_or_raises(db: Database): users = create_users(db) user = users[0] with db.session() as session: result = session.one_or_none( sa.text("SELECT * FROM users WHERE id = :id"), params={"id": user.id}) assert not isinstance(result, User) assert result.id == user.id assert result.name == user.name result = session.one_or_none( sa.text("SELECT * FROM users WHERE id = :id"), params={"id": 0}) assert result is None with pytest.raises(MultipleResultsFound): with db.session() as session: session.one_or_none(sa.text("SELECT * FROM users"))
def test_database_reflect(tmp_path: Path): db_file = tmp_path / "reflect.db" uri = f"sqlite:///{db_file}" model_collection = create_model_collection() model_class = model_collection["model_class"] model_tables = model_collection["tables"] Database(uri, model_class=model_class).create_all() db = Database(uri) assert len(db.tables) == 0 db.reflect() assert len(db.tables) == len(model_tables) model_tables_by_name = {table.name: table for table in model_tables} for table_name, _table in db.tables.items(): assert table_name in model_tables_by_name
def test_database_models(): model_collection = create_model_collection() model_class = model_collection["model_class"] models = model_collection["models"] db = Database("sqlite://", model_class=model_class) assert len(db.models) == len(models) for _model_name, model in db.models.items(): orig_model = models[models.index(model)] assert model is orig_model
def test_database_tables(): model_collection = create_model_collection() model_class = model_collection["model_class"] model_tables = model_collection["tables"] db = Database("sqlite://", model_class=model_class) assert len(db.tables) == len(model_tables) for table_name, table in db.tables.items(): assert table in model_tables model_table = model_tables[model_tables.index(table)] assert model_table.name == table_name
def filedb(tmp_path: Path) -> t.Generator[Database, None, None]: dbpath = tmp_path / "test.db" uri = f"sqlite:///{dbpath}" _db = Database(uri, model_class=Model) _db.create_all() yield _db _db.close()
def db() -> t.Generator[Database, None, None]: uri = "sqlite://" echo = False _db = Database(uri, model_class=Model, echo=echo) _db.create_all() yield _db _db.close()
def test_database_drop_all(): model_collection = create_model_collection() model_class = model_collection["model_class"] model_tables = model_collection["tables"] db = Database("sqlite://", model_class=model_class) conn = db.connect() db.create_all() count_tables = sa.text("SELECT COUNT(name) FROM sqlite_master") assert conn.execute(count_tables).scalar_one() == len(model_tables) db.drop_all() assert conn.execute(count_tables).scalar_one() == 0
def test_session_save_all__inserts_and_updates_multiple_types(db: Database): existing_users = [User(name="uA"), User(name="uB"), User(name="uC")] new_users = [User(name="u1"), User(name="u2"), User(name="u3")] existing_groups = [Group(name="gA"), Group(name="gB"), Group(name="gC")] new_groups = [Group(name="g1"), Group(name="g2"), Group(name="g3")] with db.begin(expire_on_commit=False) as session: session.save_all(existing_users) session.save_all(existing_groups) all_models = existing_users + existing_groups + new_users + new_groups # type: ignore all_users = existing_users + new_users all_groups = existing_groups + new_groups with db.begin() as session: session.save_all(all_models) with db.session() as session: count_users = sa.select(sa.func.count(User.id)) assert session.one(count_users) == len(all_users) count_groups = sa.select(sa.func.count(Group.id)) assert session.one(count_groups) == len(all_groups)