Replace the legacy Session.query() API #17

Merged
alexander merged 11 commits from sqlalchemy-select into develop 2026-12-02 00:38:24 +01:00
27 changed files with 297 additions and 216 deletions

View file

@ -68,7 +68,9 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
# Input validation.
try:
city_obj = db.session.query(db.City).filter_by(name=city.title()).one()
city_obj = db.session.scalars(
sa.select(db.City).filter_by(name=city.title()),
).one()
except sa_exc.NoResultFound:
click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"')
sys.exit(1)
@ -104,15 +106,14 @@ def tactical_heuristic( # noqa:C901,D417,DOC001
# Important: this check may need to be adapted once further
# commands are added the make `Forecast`s without the heuristic!
# Continue with forecasting on the day the last prediction was made ...
last_predict_at = (
db.session.query(sa.func.max(db.Forecast.start_at))
last_predict_at = db.session.scalar(
sa.select(sa.func.max(db.Forecast.start_at))
.join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id)
.join(db.Grid, db.Pixel.grid_id == db.Grid.id)
.filter(db.Forecast.pixel == pixel)
.filter(db.Grid.side_length == side_length)
.filter(db.Forecast.time_step == time_step)
.filter(db.Forecast.train_horizon == train_horizon)
.scalar()
.where(db.Forecast.pixel == pixel)
.where(db.Grid.side_length == side_length)
.where(db.Forecast.time_step == time_step)
.where(db.Forecast.train_horizon == train_horizon),
)
# ... or start `train_horizon` weeks after the first `Order`
# if no `Forecast`s are in the database yet.

View file

@ -1,6 +1,7 @@
"""CLI script to create pixel grids."""
import click
import sqlalchemy as sa
from velofy import config as pkg_config
from velofy import db
@ -20,7 +21,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24
All data are persisted to the database.
"""
cities = db.session.query(db.City).all()
cities = db.session.scalars(sa.select(db.City)).all()
click.echo(f"{len(cities)} cities retrieved from the database")
for city in cities:
@ -37,11 +38,11 @@ def gridify() -> None: # pragma: no cover note:b1f68d24
# Because the number of assigned addresses is the same across
# different `side_length`s, we can take the last `grid` from the `city`.
last_grid_id = grid.id # type: ignore[possibly-undefined]
n_assigned = (
db.session.query(db.AddressPixelAssociation)
.filter(db.AddressPixelAssociation.grid_id == last_grid_id)
.count()
)
n_assigned = db.session.execute(
sa.select(sa.func.count())
.select_from(db.AddressPixelAssociation)
.where(db.AddressPixelAssociation.grid_id == last_grid_id),
).scalar_one()
click.echo(
f"=> Assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}", # noqa:E501
)

View file

@ -151,12 +151,11 @@ class Path(meta.Base):
first, second = sorted(pair, key=lambda address: address.id)
# If there is no `Path` object in the database ...
path = (
db.session.query(cls)
.filter(cls.first_address == first)
.filter(cls.second_address == second)
.first()
)
path = db.session.scalars(
sa.select(cls)
.where(cls.first_address == first)
.where(cls.second_address == second),
).first()
# ... create a new one.
if path is None:
air_distance = geo_distance.great_circle(

View file

@ -163,29 +163,25 @@ class City(meta.Base):
`.map` for convenience in interactive usage
"""
# Obtain all primary `Address`es in the city that host `Restaurant`s.
addresses = (
db.session.query(db.Address)
.filter(
addresses = db.session.scalars(
sa.select(db.Address).where(
db.Address.id.in_(
db.session.query(db.Address.primary_id)
sa.select(db.Address.primary_id)
.join(db.Restaurant, db.Address.id == db.Restaurant.address_id)
.filter(db.Address.city == self)
.distinct()
.all(),
.where(db.Address.city == self)
.distinct(),
),
)
.all()
)
),
).all()
for address in addresses:
# Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's.
restaurants = (
db.session.query(db.Restaurant)
restaurants = db.session.scalars(
sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id)
.all()
)
.where(db.Address.primary_id == address.id),
).all()
if len(restaurants) == 1:
tooltip = f"{restaurants[0].name} (#{restaurants[0].id})"
else:
@ -195,12 +191,11 @@ class City(meta.Base):
if order_counts:
# Calculate the number of orders for ALL restaurants ...
n_orders = (
db.session.query(db.Order.id)
n_orders = db.session.execute(
sa.select(sa.func.count(db.Order.id))
.join(db.Address, db.Order.pickup_address_id == db.Address.id)
.filter(db.Address.primary_id == address.id)
.count()
)
.where(db.Address.primary_id == address.id),
).scalar_one()
# ... and adjust the size of the red dot on the `.map`.
if n_orders >= 1000:
radius = 20

View file

@ -1,13 +1,12 @@
"""Provide connection utils for the ORM layer.
This module defines a fully configured `session` object
to be used as a global within the `velofy` package.
If a database is not guaranteed to be available, it is set to `None`.
That is the case on the CI server.
The `session` object is used as a global within the `velofy` package,
like `db.session` in Flask-SQLAlchemy: It is a proxy to one session per thread.
The engine and the session are only created on first use;
so, importing the package does not require a database.
"""
import os
import functools
import typing as t
import sqlalchemy as sa
@ -16,10 +15,18 @@ from sqlalchemy import orm
import velofy
if os.getenv("TESTING"):
# Placeholder that the test fixtures replace
session: orm.Session = None # type: ignore[assignment]
@functools.cache
def get_engine() -> sa.Engine:
"""The engine for the configured `DATABASE_URI`, created on first use."""
return sa.create_engine(t.cast(str, velofy.config.DATABASE_URI))
else: # pragma: no cover
engine = sa.create_engine(t.cast(str, velofy.config.DATABASE_URI))
session = orm.Session(bind=engine)
# `scoped_session()` accepts any callable creating sessions
# while its type stubs expect a `sessionmaker`
# => The lambda defers creating the engine to first use.
session: orm.scoped_session[orm.Session] = orm.scoped_session(
t.cast(
"orm.sessionmaker[orm.Session]",
lambda: orm.Session(bind=get_engine()),
),
)

View file

@ -71,32 +71,26 @@ class Customer(meta.Base):
# Obtain all primary `Address`es where
# at least one delivery was made to `self`.
delivery_addresses = (
db.session.query(db.Address)
.filter(
delivery_addresses = db.session.scalars(
sa.select(db.Address).where(
db.Address.id.in_(
row.primary_id
for row in (
db.session.query(db.Address.primary_id)
.join(db.Order, db.Address.id == db.Order.delivery_address_id)
.filter(db.Order.customer_id == self.id)
.distinct()
.all()
)
sa.select(db.Address.primary_id)
.join(db.Order, db.Address.id == db.Order.delivery_address_id)
.where(db.Order.customer_id == self.id)
.distinct(),
),
)
.all()
)
),
).all()
for address in delivery_addresses:
if order_counts:
n_orders = (
db.session.query(db.Order)
n_orders = db.session.execute(
sa.select(sa.func.count())
.select_from(db.Order)
.join(db.Address, db.Order.delivery_address_id == db.Address.id)
.filter(db.Order.customer_id == self.id)
.filter(db.Address.primary_id == address.id)
.count()
)
.where(db.Order.customer_id == self.id)
.where(db.Address.primary_id == address.id),
).scalar_one()
if n_orders >= 25:
radius = 20
elif n_orders >= 10:
@ -123,30 +117,26 @@ class Customer(meta.Base):
)
if restaurants:
pickup_addresses = (
db.session.query(db.Address)
.filter(
pickup_addresses = db.session.scalars(
sa.select(db.Address).where(
db.Address.id.in_(
db.session.query(db.Address.primary_id)
sa.select(db.Address.primary_id)
.join(db.Order, db.Address.id == db.Order.pickup_address_id)
.filter(db.Order.customer_id == self.id)
.distinct()
.all(),
.where(db.Order.customer_id == self.id)
.distinct(),
),
)
.all()
)
),
).all()
for address in pickup_addresses:
# Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's.
# We cannot show the `Order.restaurant.name` due to the aggregation.
restaurants_at_address = (
db.session.query(db.Restaurant)
restaurants_at_address = db.session.scalars(
sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id)
.all()
)
.where(db.Address.primary_id == address.id),
).all()
if len(restaurants_at_address) == 1:
restaurant = restaurants_at_address[0]
tooltip = f"{restaurant.name} (#{restaurant.id})"
@ -155,13 +145,13 @@ class Customer(meta.Base):
tooltip = f"Restaurants {ids}"
if order_counts:
n_orders = (
db.session.query(db.Order)
n_orders = db.session.execute(
sa.select(sa.func.count())
.select_from(db.Order)
.join(db.Address, db.Order.pickup_address_id == db.Address.id)
.filter(db.Order.customer_id == self.id)
.filter(db.Address.primary_id == address.id)
.count()
)
.where(db.Order.customer_id == self.id)
.where(db.Address.primary_id == address.id),
).scalar_one()
if n_orders >= 25:
radius = 20
elif n_orders >= 10:

View file

@ -91,10 +91,14 @@ class Grid(meta.Base):
# `Pixel`s grouped by `.n_x`-`.n_y` coordinates.
pixels = {}
# `.unique()` because the `JOIN` yields an `Address` once per `Order`.
pickup_addresses = (
db.session.query(db.Address)
.join(db.Order, db.Address.id == db.Order.pickup_address_id)
.filter(db.Address.city == city)
db.session.scalars(
sa.select(db.Address)
.join(db.Order, db.Address.id == db.Order.pickup_address_id)
.where(db.Address.city == city),
)
.unique()
.all()
)

View file

@ -140,14 +140,15 @@ class Pixel(meta.Base):
@functools.cached_property
def restaurants(self) -> list["db.Restaurant"]: # pragma: no cover
"""Obtain all `Restaurant`s in `self`."""
return (
db.session.query(db.Restaurant)
.join(
db.AddressPixelAssociation,
db.Restaurant.address_id == db.AddressPixelAssociation.address_id,
)
.filter(db.AddressPixelAssociation.pixel_id == self.id)
.all()
return list(
db.session.scalars(
sa.select(db.Restaurant)
.join(
db.AddressPixelAssociation,
db.Restaurant.address_id == db.AddressPixelAssociation.address_id,
)
.where(db.AddressPixelAssociation.pixel_id == self.id),
).all(),
)
def clear_map(self) -> t.Self: # pragma: no cover
@ -203,38 +204,32 @@ class Pixel(meta.Base):
if restaurants:
# Obtain all primary `Address`es in the city that host `Restaurant`s
# and are in the `self` `Pixel`.
addresses = (
db.session.query(db.Address)
.filter(
addresses = db.session.scalars(
sa.select(db.Address).where(
db.Address.id.in_(
(
db.session.query(db.Address.primary_id)
.join(
db.Restaurant,
db.Address.id == db.Restaurant.address_id,
)
.join(
db.AddressPixelAssociation,
db.Address.id == db.AddressPixelAssociation.address_id,
)
.filter(db.AddressPixelAssociation.pixel_id == self.id)
sa.select(db.Address.primary_id)
.join(
db.Restaurant,
db.Address.id == db.Restaurant.address_id,
)
.distinct()
.all(),
.join(
db.AddressPixelAssociation,
db.Address.id == db.AddressPixelAssociation.address_id,
)
.where(db.AddressPixelAssociation.pixel_id == self.id)
.distinct(),
),
)
.all()
)
),
).all()
for address in addresses:
# Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's.
restaurants_at_address = (
db.session.query(db.Restaurant)
restaurants_at_address = db.session.scalars(
sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id)
.all()
)
.where(db.Address.primary_id == address.id),
).all()
if len(restaurants_at_address) == 1:
restaurant = restaurants_at_address[0]
tooltip = f"{restaurant.name} (#{restaurant.id})"
@ -244,12 +239,11 @@ class Pixel(meta.Base):
if order_counts:
# Calculate the number of orders for ALL restaurants ...
n_orders = (
db.session.query(db.Order.id)
n_orders = db.session.execute(
sa.select(sa.func.count(db.Order.id))
.join(db.Address, db.Order.pickup_address_id == db.Address.id)
.filter(db.Address.primary_id == address.id)
.count()
)
.where(db.Address.primary_id == address.id),
).scalar_one()
# ... and adjust the size of the red dot on the `.map`.
if n_orders >= 1000:
radius = 20

View file

@ -112,35 +112,32 @@ class Restaurant(meta.Base):
if customers:
# Obtain all primary `Address`es in the city that
# received at least one delivery from `self`.
delivery_addresses = (
db.session.query(db.Address)
.filter(
delivery_addresses = db.session.scalars(
sa.select(db.Address).where(
db.Address.id.in_(
row.primary_id
for row in (
db.session.query(db.Address.primary_id)
.join(
db.Order,
db.Address.id == db.Order.delivery_address_id,
)
.filter(db.Order.restaurant_id == self.id)
.distinct()
.all()
sa.select(db.Address.primary_id)
.join(
db.Order,
db.Address.id == db.Order.delivery_address_id,
)
.where(db.Order.restaurant_id == self.id)
.distinct(),
),
)
.all()
)
),
).all()
for address in delivery_addresses:
if order_counts:
n_orders = (
db.session.query(db.Order)
.join(db.Address, db.Order.delivery_address_id == db.Address.id)
.filter(db.Order.restaurant_id == self.id)
.filter(db.Address.primary_id == address.id)
.count()
)
n_orders = db.session.execute(
sa.select(sa.func.count())
.select_from(db.Order)
.join(
db.Address,
db.Order.delivery_address_id == db.Address.id,
)
.where(db.Order.restaurant_id == self.id)
.where(db.Address.primary_id == address.id),
).scalar_one()
if n_orders >= 25:
radius = 20
elif n_orders >= 10:

View file

@ -5,6 +5,7 @@ import datetime as dt
import typing as t
import pandas as pd
import sqlalchemy as sa
from velofy import db
from velofy.forecasts import timify
@ -80,15 +81,15 @@ class ForecastingModelABC(abc.ABC):
Raises:
RuntimeError: `*Model.predict()` misses the prediction for `predict_at`
"""
if (
cached_forecast := db.session.query(db.Forecast)
.filter_by(pixel=pixel)
.filter_by(start_at=predict_at)
.filter_by(time_step=self._order_history.time_step)
.filter_by(train_horizon=train_horizon)
.filter_by(model=self.name)
.first()
):
if cached_forecast := db.session.scalars(
sa.select(db.Forecast).filter_by(
pixel=pixel,
start_at=predict_at,
time_step=self._order_history.time_step,
train_horizon=train_horizon,
model=self.name,
),
).one_or_none():
return cached_forecast
# Horizontal and real-time `*Model`s return a `pd.DataFrame` with one

View file

@ -6,6 +6,7 @@ in the CLI layer need access to the database.
import os
import random
import typing as t
import pytest
import sqlalchemy as sa
@ -91,7 +92,7 @@ def db_connection(request):
@pytest.fixture
def db_session(db_connection):
def db_session(db_connection, monkeypatch):
"""A SQLAlchemy session that rolls back everything after a test case."""
# Begin the outermost transaction
# that is rolled back at the end of each test case.
@ -104,7 +105,7 @@ def db_session(db_connection):
# Monkey patch the package's global `session` object,
# which is used heavily in the code base.
db.session = session
monkeypatch.setattr(db, "session", session)
try:
yield session
@ -115,6 +116,24 @@ def db_session(db_connection):
transaction.rollback()
class _NoSession:
"""Placeholder for `db.session` in tests without the `db_session` fixture."""
def __getattr__(self, _name: str) -> t.NoReturn:
msg = "Use the `db_session` fixture to access the database"
raise RuntimeError(msg)
@pytest.fixture(autouse=True)
def _no_global_session(monkeypatch):
"""Prevent tests from opening real sessions via `db.session`.
Such a session would hold locks in the test schema
and block the `DROP SCHEMA` at the end of the test run.
"""
monkeypatch.setattr(db, "session", _NoSession())
@pytest.fixture(autouse=True)
def _seed_random() -> None:
"""Make the fake data reproducible across test runs."""

View file

@ -1,6 +1,7 @@
"""Integration test for the `velofy.console.gridify` module."""
import pytest
import sqlalchemy as sa
import velofy
from velofy import db
@ -50,5 +51,5 @@ def test_two_pixels_with_two_addresses(
assert result.exit_code == 0
assert db_session.query(db.Grid).count() == 1
assert db_session.query(db.Pixel).count() == 2
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Grid)) == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Pixel)) == 2

View file

@ -31,12 +31,18 @@ class TestConstraints:
def test_insert_into_into_database(self, db_session, replayed_order):
"""Insert an instance into the (empty) database."""
assert db_session.query(db.ReplayedOrder).count() == 0
assert (
db_session.scalar(sa.select(sa.func.count()).select_from(db.ReplayedOrder))
== 0
)
db_session.add(replayed_order)
db_session.commit()
assert db_session.query(db.ReplayedOrder).count() == 1
assert (
db_session.scalar(sa.select(sa.func.count()).select_from(db.ReplayedOrder))
== 1
)
def test_delete_a_referenced_simulation(self, db_session, replayed_order):
"""Remove a record that is referenced with a FK."""
@ -202,12 +208,12 @@ class TestConstraints:
dispatch_at=scheduled_delivery_at + dt.timedelta(hours=1),
)
assert db_session.query(db.Order).count() == 0
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 0
db_session.add(replay_pre_order)
db_session.commit()
assert db_session.query(db.Order).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Order)) == 1
def test_scheduled_order_too_late(self, db_session, make_replay_order):
"""Insert an instance with invalid data."""

View file

@ -29,12 +29,16 @@ class TestConstraints:
def test_insert_into_database(self, db_session, address):
"""Insert an instance into the (empty) database."""
assert db_session.query(db.Address).count() == 0
assert (
db_session.scalar(sa.select(sa.func.count()).select_from(db.Address)) == 0
)
db_session.add(address)
db_session.commit()
assert db_session.query(db.Address).count() == 1
assert (
db_session.scalar(sa.select(sa.func.count()).select_from(db.Address)) == 1
)
def test_delete_a_referenced_address(self, db_session, address, make_address):
"""Remove a record that is referenced with a FK."""

View file

@ -60,12 +60,12 @@ class TestConstraints:
def test_insert_into_database(self, db_session, path):
"""Insert an instance into the (empty) database."""
assert db_session.query(db.Path).count() == 0
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0
db_session.add(path)
db_session.commit()
assert db_session.query(db.Path).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1
def test_delete_a_referenced_first_address(self, db_session, path):
"""Remove a record that is referenced with a FK."""
@ -222,11 +222,11 @@ class TestFromAddresses:
another_address,
):
"""Test instantiation of a new `Path` instance."""
assert db_session.query(db.Path).count() == 0
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0
db.Path.from_addresses(address, another_address)
assert db_session.query(db.Path).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1
def test_make_the_same_path_instance_twice(
self,
@ -235,15 +235,15 @@ class TestFromAddresses:
another_address,
):
"""Test instantiation of a new `Path` instance."""
assert db_session.query(db.Path).count() == 0
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0
db.Path.from_addresses(address, another_address)
assert db_session.query(db.Path).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1
db.Path.from_addresses(another_address, address)
assert db_session.query(db.Path).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1
def test_structure_of_return_value(self, address, another_address):
"""Test instantiation of a new `Path` instance."""
@ -323,11 +323,11 @@ class TestFromAddresses:
order,
):
"""Test instantiation of a new `Path` instance."""
assert db_session.query(db.Path).count() == 0
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0
db.Path.from_order(order)
assert db_session.query(db.Path).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1
def test_make_the_same_path_instance_from_order_twice(
self,
@ -335,15 +335,15 @@ class TestFromAddresses:
order,
):
"""Test instantiation of a new `Path` instance."""
assert db_session.query(db.Path).count() == 0
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 0
db.Path.from_order(order)
assert db_session.query(db.Path).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1
db.Path.from_order(order)
assert db_session.query(db.Path).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.Path)) == 1
def test_structure_of_return_value_from_order(self, order):
"""Test instantiation of a new `Path` instance."""

View file

@ -43,12 +43,22 @@ class TestConstraints:
def test_insert_into_database(self, db_session, assoc):
"""Insert an instance into the (empty) database."""
assert db_session.query(db.AddressPixelAssociation).count() == 0
assert (
db_session.scalar(
sa.select(sa.func.count()).select_from(db.AddressPixelAssociation),
)
== 0
)
db_session.add(assoc)
db_session.commit()
assert db_session.query(db.AddressPixelAssociation).count() == 1
assert (
db_session.scalar(
sa.select(sa.func.count()).select_from(db.AddressPixelAssociation),
)
== 1
)
def test_delete_a_referenced_address(self, db_session, assoc):
"""Remove a record that is referenced with a FK."""

View file

@ -1,6 +1,7 @@
"""Test the ORM's `City` model."""
import pytest
import sqlalchemy as sa
from velofy import db
from velofy.db import utils
@ -27,12 +28,12 @@ class TestConstraints:
def test_insert_into_database(self, db_session, city):
"""Insert an instance into the (empty) database."""
assert db_session.query(db.City).count() == 0
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.City)) == 0
db_session.add(city)
db_session.commit()
assert db_session.query(db.City).count() == 1
assert db_session.scalar(sa.select(sa.func.count()).select_from(db.City)) == 1
class TestProperties:

View file

@ -0,0 +1,23 @@
"""Test the connection utils in `velofy.db.connection`."""
import sqlalchemy as sa
from velofy import config as pkg_config
from velofy.db import connection
def test_engine_uses_the_configured_database():
"""`get_engine()` connects to the `DATABASE_URI`."""
result = connection.get_engine()
assert result.url == sa.make_url(pkg_config.DATABASE_URI)
def test_session_is_bound_to_the_engine():
"""The `session` proxy creates sessions bound to `get_engine()`."""
session = connection.session()
try:
assert session.get_bind() is connection.get_engine()
finally:
connection.session.remove()

View file

@ -1,6 +1,7 @@
"""Test the ORM's `Courier` model."""
import pytest
import sqlalchemy as sa
from sqlalchemy import exc as sa_exc
from velofy import db
@ -27,12 +28,16 @@ class TestConstraints:
def test_insert_into_database(self, db_session, courier):
"""Insert an instance into the (empty) database."""
assert db_session.query(db.Courier).count() == 0
assert (
db_session.scalar(sa.select(sa.func.count()).select_from(db.Courier)) == 0
)
db_session.add(courier)
db_session.commit()
assert db_session.query(db.Courier).count() == 1
assert (
db_session.scalar(sa.select(sa.func.count()).select_from(db.Courier)) == 1
)
def test_invalid_vehicle(self, db_session, courier):
"""Insert an instance with invalid data."""

View file

@ -1,6 +1,7 @@
"""Test the ORM's `Customer` model."""
import pytest
import sqlalchemy as sa
from velofy import db
@ -26,9 +27,13 @@ class TestConstraints:
def test_insert_into_database(self, db_session, customer):
"""Insert an instance into the (empty) database."""
assert db_session.query(db.Customer).count() == 0
assert (
db_session.scalar(sa.select(sa.func.count()).select_from(db.Customer)) == 0
)
db_session.add(customer)
db_session.commit()
assert db_session.query(db.Customer).count() == 1
assert (
db_session.scalar(sa.select(sa.func.count()).select_from(db.Customer)) == 1
)

Some files were not shown because too many files have changed in this diff Show more