From ea8f1a13e34bfce01ea66951311e5f5fb5ab967f Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Sat, 28 Nov 2026 03:08:55 +0100 Subject: [PATCH] Use double quotes --- docs/conf.py | 8 +- migrations/env.py | 10 +- ...806_23_f11cd76d2f45_create_the_database.py | 844 +++++++++--------- ...20210102_18_888e352d7526_add_pixel_grid.py | 174 ++-- ..._19_e40623e10405_add_demand_forecasting.py | 76 +- ...9_add_confidence_intervals_to_forecasts.py | 66 +- ...05e_remove_orders_from_restaurants_with.py | 58 +- ...2af85bada01_store_actuals_with_forecast.py | 18 +- ...ame_training_horizon_into_train_horizon.py | 6 +- ...301_16_b4dd0b8903a5_add_distance_matrix.py | 80 +- ...914_13_81aa304d7a6e_add_simulation_data.py | 294 +++--- noxfile.py | 326 +++---- pyproject.toml | 2 - src/velofy/__init__.py | 12 +- src/velofy/configuration.py | 48 +- src/velofy/console/__init__.py | 2 +- src/velofy/console/decorators.py | 8 +- src/velofy/console/forecasts.py | 26 +- src/velofy/console/gridify.py | 12 +- src/velofy/console/main.py | 12 +- src/velofy/db/addresses.py | 60 +- src/velofy/db/addresses_addresses.py | 76 +- src/velofy/db/addresses_pixels.py | 32 +- src/velofy/db/cities.py | 20 +- src/velofy/db/connection.py | 2 +- src/velofy/db/couriers.py | 24 +- src/velofy/db/customers.py | 16 +- src/velofy/db/forecasts.py | 66 +- src/velofy/db/grids.py | 20 +- src/velofy/db/meta.py | 10 +- src/velofy/db/orders.py | 286 +++--- src/velofy/db/pixels.py | 42 +- src/velofy/db/replay/orders.py | 176 ++-- src/velofy/db/replay/simulations.py | 20 +- src/velofy/db/restaurants.py | 30 +- src/velofy/db/utils/colors.py | 4 +- src/velofy/db/utils/locations.py | 16 +- src/velofy/forecasts/methods/arima.py | 18 +- src/velofy/forecasts/methods/decomposition.py | 38 +- src/velofy/forecasts/methods/ets.py | 18 +- .../forecasts/methods/extrapolate_season.py | 14 +- src/velofy/forecasts/models/base.py | 2 +- .../forecasts/models/tactical/horizontal.py | 34 +- src/velofy/forecasts/models/tactical/other.py | 24 +- .../forecasts/models/tactical/realtime.py | 44 +- .../forecasts/models/tactical/vertical.py | 44 +- src/velofy/forecasts/timify.py | 58 +- src/velofy/init_r.py | 4 +- tests/conftest.py | 24 +- tests/console/test_gridify.py | 2 +- tests/console/test_main.py | 38 +- tests/db/fake_data/factories/addresses.py | 12 +- tests/db/fake_data/factories/couriers.py | 4 +- tests/db/fake_data/factories/customers.py | 2 +- tests/db/fake_data/factories/orders/ad_hoc.py | 2 +- .../db/fake_data/factories/orders/replayed.py | 2 +- tests/db/fake_data/factories/restaurants.py | 2 +- tests/db/fake_data/fixture_makers.py | 2 +- tests/db/fake_data/static_fixtures.py | 28 +- tests/db/replay/test_orders.py | 230 ++--- tests/db/replay/test_simulations.py | 2 +- tests/db/test_addresses.py | 22 +- tests/db/test_addresses_addresses.py | 418 ++++----- tests/db/test_addresses_pixels.py | 10 +- tests/db/test_cities.py | 14 +- tests/db/test_couriers.py | 22 +- tests/db/test_customer.py | 2 +- tests/db/test_forecasts.py | 74 +- tests/db/test_grids.py | 10 +- tests/db/test_orders.py | 300 +++---- tests/db/test_pixels.py | 16 +- tests/db/test_restaurants.py | 8 +- tests/db/utils/test_locations.py | 22 +- tests/forecasts/conftest.py | 18 +- tests/forecasts/methods/test_decomposition.py | 64 +- tests/forecasts/methods/test_predictions.py | 20 +- tests/forecasts/test_models.py | 18 +- .../forecasts/timify/test_aggregate_orders.py | 48 +- .../forecasts/timify/test_avg_daily_demand.py | 18 +- .../forecasts/timify/test_make_time_series.py | 44 +- tests/forecasts/timify/test_order_history.py | 10 +- tests/test_config.py | 80 +- tests/test_version.py | 62 +- 83 files changed, 2464 insertions(+), 2466 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 255ae4d..21bdfdb 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -5,11 +5,11 @@ import velofy project = velofy.__pkg_name__ author = velofy.__author__ -copyright = f'2020, {author}' +copyright = f"2020, {author}" version = release = velofy.__version__ extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.napoleon', - 'sphinx_autodoc_typehints', + "sphinx.ext.autodoc", + "sphinx.ext.napoleon", + "sphinx_autodoc_typehints", ] diff --git a/migrations/env.py b/migrations/env.py index 40e1288..f2f2f71 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -12,7 +12,7 @@ from velofy import db # Disable the --sql option, a.k.a, the "offline mode". if context.is_offline_mode(): - raise NotImplementedError('The --sql option is not implemented in this project') + raise NotImplementedError("The --sql option is not implemented in this project") # Set up the default Python logger from the alembic.ini file. @@ -22,8 +22,8 @@ log_config.fileConfig(context.config.config_file_name) def include_object(obj, _name, type_, _reflected, _compare_to): """Only include the clean schema into --autogenerate migrations.""" if ( - type_ in {'table', 'column'} - and hasattr(obj, 'schema') # => fix for rare edge case + type_ in {"table", "column"} + and hasattr(obj, "schema") # => fix for rare edge case and obj.schema != velofy_config.CLEAN_SCHEMA ): return False @@ -38,10 +38,10 @@ with engine.connect() as connection: connection=connection, include_object=include_object, target_metadata=db.Base.metadata, - version_table='{alembic_table}{test_schema}'.format( + version_table="{alembic_table}{test_schema}".format( alembic_table=velofy_config.ALEMBIC_TABLE, test_schema=( - f'_{velofy_config.CLEAN_SCHEMA}' if os.getenv('TESTING') else '' + f"_{velofy_config.CLEAN_SCHEMA}" if os.getenv("TESTING") else "" ), ), version_table_schema=velofy_config.ALEMBIC_TABLE_SCHEMA, diff --git a/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py b/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py index 69b5a0e..f4ff769 100644 --- a/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py +++ b/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py @@ -12,39 +12,39 @@ from sqlalchemy.dialects import postgresql from velofy import configuration -revision = 'f11cd76d2f45' +revision = "f11cd76d2f45" down_revision = None branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): """Upgrade to revision f11cd76d2f45.""" - op.execute(f'CREATE SCHEMA {config.CLEAN_SCHEMA};') + op.execute(f"CREATE SCHEMA {config.CLEAN_SCHEMA};") op.create_table( - 'cities', - sa.Column('id', sa.SmallInteger(), autoincrement=False, nullable=False), - sa.Column('name', sa.Unicode(length=10), nullable=False), - sa.Column('kml', sa.UnicodeText(), nullable=False), - sa.Column('center_latitude', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('center_longitude', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('northeast_latitude', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('northeast_longitude', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('southwest_latitude', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('southwest_longitude', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('initial_zoom', sa.SmallInteger(), nullable=False), - sa.PrimaryKeyConstraint('id', name=op.f('pk_cities')), + "cities", + sa.Column("id", sa.SmallInteger(), autoincrement=False, nullable=False), + sa.Column("name", sa.Unicode(length=10), nullable=False), + sa.Column("kml", sa.UnicodeText(), nullable=False), + sa.Column("center_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("center_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("northeast_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("northeast_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("southwest_latitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("southwest_longitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("initial_zoom", sa.SmallInteger(), nullable=False), + sa.PrimaryKeyConstraint("id", name=op.f("pk_cities")), *( [ sa.ForeignKeyConstraint( - ['id'], - [f'{config.ORIGINAL_SCHEMA}.cities.id'], - name=op.f('pk_cities_sanity'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["id"], + [f"{config.ORIGINAL_SCHEMA}.cities.id"], + name=op.f("pk_cities_sanity"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), ] if not config.TESTING @@ -53,43 +53,43 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) op.create_table( - 'couriers', - sa.Column('id', sa.Integer(), autoincrement=False, nullable=False), - sa.Column('created_at', sa.DateTime(), nullable=False), - sa.Column('vehicle', sa.Unicode(length=10), nullable=False), - sa.Column('speed', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('capacity', sa.SmallInteger(), nullable=False), - sa.Column('pay_per_hour', sa.SmallInteger(), nullable=False), - sa.Column('pay_per_order', sa.SmallInteger(), nullable=False), + "couriers", + sa.Column("id", sa.Integer(), autoincrement=False, nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("vehicle", sa.Unicode(length=10), nullable=False), + sa.Column("speed", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("capacity", sa.SmallInteger(), nullable=False), + sa.Column("pay_per_hour", sa.SmallInteger(), nullable=False), + sa.Column("pay_per_order", sa.SmallInteger(), nullable=False), sa.CheckConstraint( "vehicle IN ('bicycle', 'motorcycle')", - name=op.f('ck_couriers_on_available_vehicle_types'), + name=op.f("ck_couriers_on_available_vehicle_types"), ), sa.CheckConstraint( - '0 <= capacity AND capacity <= 200', - name=op.f('ck_couriers_on_capacity_under_200_liters'), + "0 <= capacity AND capacity <= 200", + name=op.f("ck_couriers_on_capacity_under_200_liters"), ), sa.CheckConstraint( - '0 <= pay_per_hour AND pay_per_hour <= 1500', - name=op.f('ck_couriers_on_realistic_pay_per_hour'), + "0 <= pay_per_hour AND pay_per_hour <= 1500", + name=op.f("ck_couriers_on_realistic_pay_per_hour"), ), sa.CheckConstraint( - '0 <= pay_per_order AND pay_per_order <= 650', - name=op.f('ck_couriers_on_realistic_pay_per_order'), + "0 <= pay_per_order AND pay_per_order <= 650", + name=op.f("ck_couriers_on_realistic_pay_per_order"), ), sa.CheckConstraint( - '0 <= speed AND speed <= 30', - name=op.f('ck_couriers_on_realistic_speed'), + "0 <= speed AND speed <= 30", + name=op.f("ck_couriers_on_realistic_speed"), ), - sa.PrimaryKeyConstraint('id', name=op.f('pk_couriers')), + sa.PrimaryKeyConstraint("id", name=op.f("pk_couriers")), *( [ sa.ForeignKeyConstraint( - ['id'], - [f'{config.ORIGINAL_SCHEMA}.couriers.id'], - name=op.f('pk_couriers_sanity'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["id"], + [f"{config.ORIGINAL_SCHEMA}.couriers.id"], + name=op.f("pk_couriers_sanity"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), ] if not config.TESTING @@ -98,63 +98,63 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) op.create_table( - 'customers', - sa.Column('id', sa.Integer(), autoincrement=False, nullable=False), - sa.PrimaryKeyConstraint('id', name=op.f('pk_customers')), + "customers", + sa.Column("id", sa.Integer(), autoincrement=False, nullable=False), + sa.PrimaryKeyConstraint("id", name=op.f("pk_customers")), schema=config.CLEAN_SCHEMA, ) op.create_table( - 'addresses', - sa.Column('id', sa.Integer(), autoincrement=False, nullable=False), - sa.Column('primary_id', sa.Integer(), nullable=False), - sa.Column('created_at', sa.DateTime(), nullable=False), - sa.Column('place_id', sa.Unicode(length=120), nullable=False), - sa.Column('latitude', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('longitude', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.Column('city_id', sa.SmallInteger(), nullable=False), - sa.Column('city', sa.Unicode(length=25), nullable=False), - sa.Column('zip_code', sa.Integer(), nullable=False), - sa.Column('street', sa.Unicode(length=80), nullable=False), - sa.Column('floor', sa.SmallInteger(), nullable=True), + "addresses", + sa.Column("id", sa.Integer(), autoincrement=False, nullable=False), + sa.Column("primary_id", sa.Integer(), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("place_id", sa.Unicode(length=120), nullable=False), + sa.Column("latitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("longitude", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.Column("city_id", sa.SmallInteger(), nullable=False), + sa.Column("city", sa.Unicode(length=25), nullable=False), + sa.Column("zip_code", sa.Integer(), nullable=False), + sa.Column("street", sa.Unicode(length=80), nullable=False), + sa.Column("floor", sa.SmallInteger(), nullable=True), sa.CheckConstraint( - '-180 <= longitude AND longitude <= 180', - name=op.f('ck_addresses_on_longitude_between_180_degrees'), + "-180 <= longitude AND longitude <= 180", + name=op.f("ck_addresses_on_longitude_between_180_degrees"), ), sa.CheckConstraint( - '-90 <= latitude AND latitude <= 90', - name=op.f('ck_addresses_on_latitude_between_90_degrees'), + "-90 <= latitude AND latitude <= 90", + name=op.f("ck_addresses_on_latitude_between_90_degrees"), ), sa.CheckConstraint( - '0 <= floor AND floor <= 40', - name=op.f('ck_addresses_on_realistic_floor'), + "0 <= floor AND floor <= 40", + name=op.f("ck_addresses_on_realistic_floor"), ), sa.CheckConstraint( - '30000 <= zip_code AND zip_code <= 99999', - name=op.f('ck_addresses_on_valid_zip_code'), + "30000 <= zip_code AND zip_code <= 99999", + name=op.f("ck_addresses_on_valid_zip_code"), ), sa.ForeignKeyConstraint( - ['city_id'], - [f'{config.CLEAN_SCHEMA}.cities.id'], - name=op.f('fk_addresses_to_cities_via_city_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["city_id"], + [f"{config.CLEAN_SCHEMA}.cities.id"], + name=op.f("fk_addresses_to_cities_via_city_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['primary_id'], - [f'{config.CLEAN_SCHEMA}.addresses.id'], - name=op.f('fk_addresses_to_addresses_via_primary_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["primary_id"], + [f"{config.CLEAN_SCHEMA}.addresses.id"], + name=op.f("fk_addresses_to_addresses_via_primary_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), - sa.PrimaryKeyConstraint('id', name=op.f('pk_addresses')), + sa.PrimaryKeyConstraint("id", name=op.f("pk_addresses")), *( [ sa.ForeignKeyConstraint( - ['id'], - [f'{config.ORIGINAL_SCHEMA}.addresses.id'], - name=op.f('pk_addresses_sanity'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["id"], + [f"{config.ORIGINAL_SCHEMA}.addresses.id"], + name=op.f("pk_addresses_sanity"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), ] if not config.TESTING @@ -163,60 +163,60 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_addresses_on_city_id'), - 'addresses', - ['city_id'], + op.f("ix_addresses_on_city_id"), + "addresses", + ["city_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_addresses_on_place_id'), - 'addresses', - ['place_id'], + op.f("ix_addresses_on_place_id"), + "addresses", + ["place_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_addresses_on_primary_id'), - 'addresses', - ['primary_id'], + op.f("ix_addresses_on_primary_id"), + "addresses", + ["primary_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_addresses_on_zip_code'), - 'addresses', - ['zip_code'], + op.f("ix_addresses_on_zip_code"), + "addresses", + ["zip_code"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_table( - 'restaurants', - sa.Column('id', sa.SmallInteger(), autoincrement=False, nullable=False), - sa.Column('created_at', sa.DateTime(), nullable=False), - sa.Column('name', sa.Unicode(length=45), nullable=False), - sa.Column('address_id', sa.Integer(), nullable=False), - sa.Column('estimated_prep_duration', sa.SmallInteger(), nullable=False), + "restaurants", + sa.Column("id", sa.SmallInteger(), autoincrement=False, nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("name", sa.Unicode(length=45), nullable=False), + sa.Column("address_id", sa.Integer(), nullable=False), + sa.Column("estimated_prep_duration", sa.SmallInteger(), nullable=False), sa.CheckConstraint( - '0 <= estimated_prep_duration AND estimated_prep_duration <= 2400', - name=op.f('ck_restaurants_on_realistic_estimated_prep_duration'), + "0 <= estimated_prep_duration AND estimated_prep_duration <= 2400", + name=op.f("ck_restaurants_on_realistic_estimated_prep_duration"), ), sa.ForeignKeyConstraint( - ['address_id'], - [f'{config.CLEAN_SCHEMA}.addresses.id'], - name=op.f('fk_restaurants_to_addresses_via_address_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["address_id"], + [f"{config.CLEAN_SCHEMA}.addresses.id"], + name=op.f("fk_restaurants_to_addresses_via_address_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), - sa.PrimaryKeyConstraint('id', name=op.f('pk_restaurants')), + sa.PrimaryKeyConstraint("id", name=op.f("pk_restaurants")), *( [ sa.ForeignKeyConstraint( - ['id'], - [f'{config.ORIGINAL_SCHEMA}.businesses.id'], - name=op.f('pk_restaurants_sanity'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["id"], + [f"{config.ORIGINAL_SCHEMA}.businesses.id"], + name=op.f("pk_restaurants_sanity"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), ] if not config.TESTING @@ -225,423 +225,423 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_restaurants_on_address_id'), - 'restaurants', - ['address_id'], + op.f("ix_restaurants_on_address_id"), + "restaurants", + ["address_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_table( - 'orders', - sa.Column('id', sa.Integer(), autoincrement=False, nullable=False), - sa.Column('delivery_id', sa.Integer(), nullable=True), - sa.Column('customer_id', sa.Integer(), nullable=False), - sa.Column('placed_at', sa.DateTime(), nullable=False), - sa.Column('ad_hoc', sa.Boolean(), nullable=False), - sa.Column('scheduled_delivery_at', sa.DateTime(), nullable=True), - sa.Column('scheduled_delivery_at_corrected', sa.Boolean(), nullable=True), - sa.Column('first_estimated_delivery_at', sa.DateTime(), nullable=True), - sa.Column('cancelled', sa.Boolean(), nullable=False), - sa.Column('cancelled_at', sa.DateTime(), nullable=True), - sa.Column('cancelled_at_corrected', sa.Boolean(), nullable=True), - sa.Column('sub_total', sa.Integer(), nullable=False), - sa.Column('delivery_fee', sa.SmallInteger(), nullable=False), - sa.Column('total', sa.Integer(), nullable=False), - sa.Column('restaurant_id', sa.SmallInteger(), nullable=False), - sa.Column('restaurant_notified_at', sa.DateTime(), nullable=True), - sa.Column('restaurant_notified_at_corrected', sa.Boolean(), nullable=True), - sa.Column('restaurant_confirmed_at', sa.DateTime(), nullable=True), - sa.Column('restaurant_confirmed_at_corrected', sa.Boolean(), nullable=True), - sa.Column('estimated_prep_duration', sa.Integer(), nullable=True), - sa.Column('estimated_prep_duration_corrected', sa.Boolean(), nullable=True), - sa.Column('estimated_prep_buffer', sa.Integer(), nullable=False), - sa.Column('courier_id', sa.Integer(), nullable=True), - sa.Column('dispatch_at', sa.DateTime(), nullable=True), - sa.Column('dispatch_at_corrected', sa.Boolean(), nullable=True), - sa.Column('courier_notified_at', sa.DateTime(), nullable=True), - sa.Column('courier_notified_at_corrected', sa.Boolean(), nullable=True), - sa.Column('courier_accepted_at', sa.DateTime(), nullable=True), - sa.Column('courier_accepted_at_corrected', sa.Boolean(), nullable=True), - sa.Column('utilization', sa.SmallInteger(), nullable=False), - sa.Column('pickup_address_id', sa.Integer(), nullable=False), - sa.Column('reached_pickup_at', sa.DateTime(), nullable=True), - sa.Column('pickup_at', sa.DateTime(), nullable=True), - sa.Column('pickup_at_corrected', sa.Boolean(), nullable=True), - sa.Column('pickup_not_confirmed', sa.Boolean(), nullable=True), - sa.Column('left_pickup_at', sa.DateTime(), nullable=True), - sa.Column('left_pickup_at_corrected', sa.Boolean(), nullable=True), - sa.Column('delivery_address_id', sa.Integer(), nullable=False), - sa.Column('reached_delivery_at', sa.DateTime(), nullable=True), - sa.Column('delivery_at', sa.DateTime(), nullable=True), - sa.Column('delivery_at_corrected', sa.Boolean(), nullable=True), - sa.Column('delivery_not_confirmed', sa.Boolean(), nullable=True), - sa.Column('courier_waited_at_delivery', sa.Boolean(), nullable=True), - sa.Column('logged_delivery_distance', sa.SmallInteger(), nullable=True), - sa.Column('logged_avg_speed', postgresql.DOUBLE_PRECISION(), nullable=True), - sa.Column('logged_avg_speed_distance', sa.SmallInteger(), nullable=True), + "orders", + sa.Column("id", sa.Integer(), autoincrement=False, nullable=False), + sa.Column("delivery_id", sa.Integer(), nullable=True), + sa.Column("customer_id", sa.Integer(), nullable=False), + sa.Column("placed_at", sa.DateTime(), nullable=False), + sa.Column("ad_hoc", sa.Boolean(), nullable=False), + sa.Column("scheduled_delivery_at", sa.DateTime(), nullable=True), + sa.Column("scheduled_delivery_at_corrected", sa.Boolean(), nullable=True), + sa.Column("first_estimated_delivery_at", sa.DateTime(), nullable=True), + sa.Column("cancelled", sa.Boolean(), nullable=False), + sa.Column("cancelled_at", sa.DateTime(), nullable=True), + sa.Column("cancelled_at_corrected", sa.Boolean(), nullable=True), + sa.Column("sub_total", sa.Integer(), nullable=False), + sa.Column("delivery_fee", sa.SmallInteger(), nullable=False), + sa.Column("total", sa.Integer(), nullable=False), + sa.Column("restaurant_id", sa.SmallInteger(), nullable=False), + sa.Column("restaurant_notified_at", sa.DateTime(), nullable=True), + sa.Column("restaurant_notified_at_corrected", sa.Boolean(), nullable=True), + sa.Column("restaurant_confirmed_at", sa.DateTime(), nullable=True), + sa.Column("restaurant_confirmed_at_corrected", sa.Boolean(), nullable=True), + sa.Column("estimated_prep_duration", sa.Integer(), nullable=True), + sa.Column("estimated_prep_duration_corrected", sa.Boolean(), nullable=True), + sa.Column("estimated_prep_buffer", sa.Integer(), nullable=False), + sa.Column("courier_id", sa.Integer(), nullable=True), + sa.Column("dispatch_at", sa.DateTime(), nullable=True), + sa.Column("dispatch_at_corrected", sa.Boolean(), nullable=True), + sa.Column("courier_notified_at", sa.DateTime(), nullable=True), + sa.Column("courier_notified_at_corrected", sa.Boolean(), nullable=True), + sa.Column("courier_accepted_at", sa.DateTime(), nullable=True), + sa.Column("courier_accepted_at_corrected", sa.Boolean(), nullable=True), + sa.Column("utilization", sa.SmallInteger(), nullable=False), + sa.Column("pickup_address_id", sa.Integer(), nullable=False), + sa.Column("reached_pickup_at", sa.DateTime(), nullable=True), + sa.Column("pickup_at", sa.DateTime(), nullable=True), + sa.Column("pickup_at_corrected", sa.Boolean(), nullable=True), + sa.Column("pickup_not_confirmed", sa.Boolean(), nullable=True), + sa.Column("left_pickup_at", sa.DateTime(), nullable=True), + sa.Column("left_pickup_at_corrected", sa.Boolean(), nullable=True), + sa.Column("delivery_address_id", sa.Integer(), nullable=False), + sa.Column("reached_delivery_at", sa.DateTime(), nullable=True), + sa.Column("delivery_at", sa.DateTime(), nullable=True), + sa.Column("delivery_at_corrected", sa.Boolean(), nullable=True), + sa.Column("delivery_not_confirmed", sa.Boolean(), nullable=True), + sa.Column("courier_waited_at_delivery", sa.Boolean(), nullable=True), + sa.Column("logged_delivery_distance", sa.SmallInteger(), nullable=True), + sa.Column("logged_avg_speed", postgresql.DOUBLE_PRECISION(), nullable=True), + sa.Column("logged_avg_speed_distance", sa.SmallInteger(), nullable=True), sa.CheckConstraint( - '0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900', - name=op.f('ck_orders_on_estimated_prep_buffer_between_0_and_900'), + "0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900", + name=op.f("ck_orders_on_estimated_prep_buffer_between_0_and_900"), ), sa.CheckConstraint( - '0 <= estimated_prep_duration AND estimated_prep_duration <= 2700', - name=op.f('ck_orders_on_estimated_prep_duration_between_0_and_2700'), + "0 <= estimated_prep_duration AND estimated_prep_duration <= 2700", + name=op.f("ck_orders_on_estimated_prep_duration_between_0_and_2700"), ), sa.CheckConstraint( - '0 <= utilization AND utilization <= 100', - name=op.f('ck_orders_on_utilization_between_0_and_100'), + "0 <= utilization AND utilization <= 100", + name=op.f("ck_orders_on_utilization_between_0_and_100"), ), sa.CheckConstraint( - '(cancelled_at IS NULL AND cancelled_at_corrected IS NULL) OR (cancelled_at IS NULL AND cancelled_at_corrected IS TRUE) OR (cancelled_at IS NOT NULL AND cancelled_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_1'), + "(cancelled_at IS NULL AND cancelled_at_corrected IS NULL) OR (cancelled_at IS NULL AND cancelled_at_corrected IS TRUE) OR (cancelled_at IS NOT NULL AND cancelled_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_1"), ), sa.CheckConstraint( - '(courier_accepted_at IS NULL AND courier_accepted_at_corrected IS NULL) OR (courier_accepted_at IS NULL AND courier_accepted_at_corrected IS TRUE) OR (courier_accepted_at IS NOT NULL AND courier_accepted_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_7'), + "(courier_accepted_at IS NULL AND courier_accepted_at_corrected IS NULL) OR (courier_accepted_at IS NULL AND courier_accepted_at_corrected IS TRUE) OR (courier_accepted_at IS NOT NULL AND courier_accepted_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_7"), ), sa.CheckConstraint( - '(courier_notified_at IS NULL AND courier_notified_at_corrected IS NULL) OR (courier_notified_at IS NULL AND courier_notified_at_corrected IS TRUE) OR (courier_notified_at IS NOT NULL AND courier_notified_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_6'), + "(courier_notified_at IS NULL AND courier_notified_at_corrected IS NULL) OR (courier_notified_at IS NULL AND courier_notified_at_corrected IS TRUE) OR (courier_notified_at IS NOT NULL AND courier_notified_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_6"), ), sa.CheckConstraint( - '(delivery_at IS NULL AND delivery_at_corrected IS NULL) OR (delivery_at IS NULL AND delivery_at_corrected IS TRUE) OR (delivery_at IS NOT NULL AND delivery_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_10'), + "(delivery_at IS NULL AND delivery_at_corrected IS NULL) OR (delivery_at IS NULL AND delivery_at_corrected IS TRUE) OR (delivery_at IS NOT NULL AND delivery_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_10"), ), sa.CheckConstraint( - '(dispatch_at IS NULL AND dispatch_at_corrected IS NULL) OR (dispatch_at IS NULL AND dispatch_at_corrected IS TRUE) OR (dispatch_at IS NOT NULL AND dispatch_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_5'), + "(dispatch_at IS NULL AND dispatch_at_corrected IS NULL) OR (dispatch_at IS NULL AND dispatch_at_corrected IS TRUE) OR (dispatch_at IS NOT NULL AND dispatch_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_5"), ), sa.CheckConstraint( - '(estimated_prep_duration IS NULL AND estimated_prep_duration_corrected IS NULL) OR (estimated_prep_duration IS NULL AND estimated_prep_duration_corrected IS TRUE) OR (estimated_prep_duration IS NOT NULL AND estimated_prep_duration_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_4'), + "(estimated_prep_duration IS NULL AND estimated_prep_duration_corrected IS NULL) OR (estimated_prep_duration IS NULL AND estimated_prep_duration_corrected IS TRUE) OR (estimated_prep_duration IS NOT NULL AND estimated_prep_duration_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_4"), ), sa.CheckConstraint( - '(left_pickup_at IS NULL AND left_pickup_at_corrected IS NULL) OR (left_pickup_at IS NULL AND left_pickup_at_corrected IS TRUE) OR (left_pickup_at IS NOT NULL AND left_pickup_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_9'), + "(left_pickup_at IS NULL AND left_pickup_at_corrected IS NULL) OR (left_pickup_at IS NULL AND left_pickup_at_corrected IS TRUE) OR (left_pickup_at IS NOT NULL AND left_pickup_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_9"), ), sa.CheckConstraint( - '(pickup_at IS NULL AND pickup_at_corrected IS NULL) OR (pickup_at IS NULL AND pickup_at_corrected IS TRUE) OR (pickup_at IS NOT NULL AND pickup_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_8'), + "(pickup_at IS NULL AND pickup_at_corrected IS NULL) OR (pickup_at IS NULL AND pickup_at_corrected IS TRUE) OR (pickup_at IS NOT NULL AND pickup_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_8"), ), sa.CheckConstraint( - '(restaurant_confirmed_at IS NULL AND restaurant_confirmed_at_corrected IS NULL) OR (restaurant_confirmed_at IS NULL AND restaurant_confirmed_at_corrected IS TRUE) OR (restaurant_confirmed_at IS NOT NULL AND restaurant_confirmed_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_3'), + "(restaurant_confirmed_at IS NULL AND restaurant_confirmed_at_corrected IS NULL) OR (restaurant_confirmed_at IS NULL AND restaurant_confirmed_at_corrected IS TRUE) OR (restaurant_confirmed_at IS NOT NULL AND restaurant_confirmed_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_3"), ), sa.CheckConstraint( - '(restaurant_notified_at IS NULL AND restaurant_notified_at_corrected IS NULL) OR (restaurant_notified_at IS NULL AND restaurant_notified_at_corrected IS TRUE) OR (restaurant_notified_at IS NOT NULL AND restaurant_notified_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_2'), + "(restaurant_notified_at IS NULL AND restaurant_notified_at_corrected IS NULL) OR (restaurant_notified_at IS NULL AND restaurant_notified_at_corrected IS TRUE) OR (restaurant_notified_at IS NOT NULL AND restaurant_notified_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_2"), ), sa.CheckConstraint( - '(scheduled_delivery_at IS NULL AND scheduled_delivery_at_corrected IS NULL) OR (scheduled_delivery_at IS NULL AND scheduled_delivery_at_corrected IS TRUE) OR (scheduled_delivery_at IS NOT NULL AND scheduled_delivery_at_corrected IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_corrections_only_for_set_value_0'), + "(scheduled_delivery_at IS NULL AND scheduled_delivery_at_corrected IS NULL) OR (scheduled_delivery_at IS NULL AND scheduled_delivery_at_corrected IS TRUE) OR (scheduled_delivery_at IS NOT NULL AND scheduled_delivery_at_corrected IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_corrections_only_for_set_value_0"), ), sa.CheckConstraint( - '(ad_hoc IS TRUE AND scheduled_delivery_at IS NULL) OR (ad_hoc IS FALSE AND scheduled_delivery_at IS NOT NULL)', # noqa:E501 - name=op.f('ck_orders_on_either_ad_hoc_or_scheduled_order'), + "(ad_hoc IS TRUE AND scheduled_delivery_at IS NULL) OR (ad_hoc IS FALSE AND scheduled_delivery_at IS NOT NULL)", # noqa:E501 + name=op.f("ck_orders_on_either_ad_hoc_or_scheduled_order"), ), sa.CheckConstraint( - 'NOT (EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800)', - name=op.f('ck_orders_on_scheduled_orders_not_within_30_minutes'), + "NOT (EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800)", + name=op.f("ck_orders_on_scheduled_orders_not_within_30_minutes"), ), sa.CheckConstraint( - 'NOT (ad_hoc IS FALSE AND ((EXTRACT(HOUR FROM scheduled_delivery_at) <= 11 AND NOT (EXTRACT(HOUR FROM scheduled_delivery_at) = 11 AND EXTRACT(MINUTE FROM scheduled_delivery_at) = 45)) OR EXTRACT(HOUR FROM scheduled_delivery_at) > 22))', # noqa:E501 - name=op.f('ck_orders_on_scheduled_orders_within_business_hours'), + "NOT (ad_hoc IS FALSE AND ((EXTRACT(HOUR FROM scheduled_delivery_at) <= 11 AND NOT (EXTRACT(HOUR FROM scheduled_delivery_at) = 11 AND EXTRACT(MINUTE FROM scheduled_delivery_at) = 45)) OR EXTRACT(HOUR FROM scheduled_delivery_at) > 22))", # noqa:E501 + name=op.f("ck_orders_on_scheduled_orders_within_business_hours"), ), sa.CheckConstraint( - 'NOT (ad_hoc IS TRUE AND (EXTRACT(HOUR FROM placed_at) < 11 OR EXTRACT(HOUR FROM placed_at) > 22))', # noqa:E501 - name=op.f('ck_orders_on_ad_hoc_orders_within_business_hours'), + "NOT (ad_hoc IS TRUE AND (EXTRACT(HOUR FROM placed_at) < 11 OR EXTRACT(HOUR FROM placed_at) > 22))", # noqa:E501 + name=op.f("ck_orders_on_ad_hoc_orders_within_business_hours"), ), sa.CheckConstraint( - 'NOT (cancelled IS FALSE AND cancelled_at IS NOT NULL)', - name=op.f('ck_orders_on_only_cancelled_orders_may_have_cancelled_at'), + "NOT (cancelled IS FALSE AND cancelled_at IS NOT NULL)", + name=op.f("ck_orders_on_only_cancelled_orders_may_have_cancelled_at"), ), sa.CheckConstraint( - 'NOT (cancelled IS TRUE AND delivery_at IS NOT NULL)', - name=op.f('ck_orders_on_cancelled_orders_must_not_be_delivered'), + "NOT (cancelled IS TRUE AND delivery_at IS NOT NULL)", + name=op.f("ck_orders_on_cancelled_orders_must_not_be_delivered"), ), sa.CheckConstraint( - 'cancelled_at > courier_accepted_at', - name=op.f('ck_orders_on_ordered_timestamps_16'), + "cancelled_at > courier_accepted_at", + name=op.f("ck_orders_on_ordered_timestamps_16"), ), sa.CheckConstraint( - 'cancelled_at > courier_notified_at', - name=op.f('ck_orders_on_ordered_timestamps_15'), + "cancelled_at > courier_notified_at", + name=op.f("ck_orders_on_ordered_timestamps_15"), ), sa.CheckConstraint( - 'cancelled_at > delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_21'), + "cancelled_at > delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_21"), ), sa.CheckConstraint( - 'cancelled_at > dispatch_at', - name=op.f('ck_orders_on_ordered_timestamps_14'), + "cancelled_at > dispatch_at", + name=op.f("ck_orders_on_ordered_timestamps_14"), ), sa.CheckConstraint( - 'cancelled_at > left_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_19'), + "cancelled_at > left_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_19"), ), sa.CheckConstraint( - 'cancelled_at > pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_18'), + "cancelled_at > pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_18"), ), sa.CheckConstraint( - 'cancelled_at > reached_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_20'), + "cancelled_at > reached_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_20"), ), sa.CheckConstraint( - 'cancelled_at > reached_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_17'), + "cancelled_at > reached_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_17"), ), sa.CheckConstraint( - 'cancelled_at > restaurant_confirmed_at', - name=op.f('ck_orders_on_ordered_timestamps_13'), + "cancelled_at > restaurant_confirmed_at", + name=op.f("ck_orders_on_ordered_timestamps_13"), ), sa.CheckConstraint( - 'cancelled_at > restaurant_notified_at', - name=op.f('ck_orders_on_ordered_timestamps_12'), + "cancelled_at > restaurant_notified_at", + name=op.f("ck_orders_on_ordered_timestamps_12"), ), sa.CheckConstraint( - 'courier_accepted_at < delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_42'), + "courier_accepted_at < delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_42"), ), sa.CheckConstraint( - 'courier_accepted_at < left_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_40'), + "courier_accepted_at < left_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_40"), ), sa.CheckConstraint( - 'courier_accepted_at < pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_39'), + "courier_accepted_at < pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_39"), ), sa.CheckConstraint( - 'courier_accepted_at < reached_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_41'), + "courier_accepted_at < reached_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_41"), ), sa.CheckConstraint( - 'courier_accepted_at < reached_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_38'), + "courier_accepted_at < reached_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_38"), ), sa.CheckConstraint( - 'courier_notified_at < courier_accepted_at', - name=op.f('ck_orders_on_ordered_timestamps_32'), + "courier_notified_at < courier_accepted_at", + name=op.f("ck_orders_on_ordered_timestamps_32"), ), sa.CheckConstraint( - 'courier_notified_at < delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_37'), + "courier_notified_at < delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_37"), ), sa.CheckConstraint( - 'courier_notified_at < left_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_35'), + "courier_notified_at < left_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_35"), ), sa.CheckConstraint( - 'courier_notified_at < pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_34'), + "courier_notified_at < pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_34"), ), sa.CheckConstraint( - 'courier_notified_at < reached_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_36'), + "courier_notified_at < reached_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_36"), ), sa.CheckConstraint( - 'courier_notified_at < reached_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_33'), + "courier_notified_at < reached_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_33"), ), sa.CheckConstraint( - 'dispatch_at < courier_accepted_at', - name=op.f('ck_orders_on_ordered_timestamps_26'), + "dispatch_at < courier_accepted_at", + name=op.f("ck_orders_on_ordered_timestamps_26"), ), sa.CheckConstraint( - 'dispatch_at < courier_notified_at', - name=op.f('ck_orders_on_ordered_timestamps_25'), + "dispatch_at < courier_notified_at", + name=op.f("ck_orders_on_ordered_timestamps_25"), ), sa.CheckConstraint( - 'dispatch_at < delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_31'), + "dispatch_at < delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_31"), ), sa.CheckConstraint( - 'dispatch_at < left_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_29'), + "dispatch_at < left_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_29"), ), sa.CheckConstraint( - 'dispatch_at < pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_28'), + "dispatch_at < pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_28"), ), sa.CheckConstraint( - 'dispatch_at < reached_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_30'), + "dispatch_at < reached_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_30"), ), sa.CheckConstraint( - 'dispatch_at < reached_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_27'), + "dispatch_at < reached_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_27"), ), sa.CheckConstraint( - 'estimated_prep_buffer % 60 = 0', - name=op.f('ck_orders_on_estimated_prep_buffer_must_be_whole_minutes'), + "estimated_prep_buffer % 60 = 0", + name=op.f("ck_orders_on_estimated_prep_buffer_must_be_whole_minutes"), ), sa.CheckConstraint( - 'estimated_prep_duration % 60 = 0', - name=op.f('ck_orders_on_estimated_prep_duration_must_be_whole_minutes'), + "estimated_prep_duration % 60 = 0", + name=op.f("ck_orders_on_estimated_prep_duration_must_be_whole_minutes"), ), sa.CheckConstraint( - 'left_pickup_at < delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_51'), + "left_pickup_at < delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_51"), ), sa.CheckConstraint( - 'left_pickup_at < reached_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_50'), + "left_pickup_at < reached_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_50"), ), sa.CheckConstraint( - 'pickup_at < delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_49'), + "pickup_at < delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_49"), ), sa.CheckConstraint( - 'pickup_at < left_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_47'), + "pickup_at < left_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_47"), ), sa.CheckConstraint( - 'pickup_at < reached_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_48'), + "pickup_at < reached_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_48"), ), sa.CheckConstraint( - 'placed_at < cancelled_at', - name=op.f('ck_orders_on_ordered_timestamps_2'), + "placed_at < cancelled_at", + name=op.f("ck_orders_on_ordered_timestamps_2"), ), sa.CheckConstraint( - 'placed_at < courier_accepted_at', - name=op.f('ck_orders_on_ordered_timestamps_7'), + "placed_at < courier_accepted_at", + name=op.f("ck_orders_on_ordered_timestamps_7"), ), sa.CheckConstraint( - 'placed_at < courier_notified_at', - name=op.f('ck_orders_on_ordered_timestamps_6'), + "placed_at < courier_notified_at", + name=op.f("ck_orders_on_ordered_timestamps_6"), ), sa.CheckConstraint( - 'placed_at < delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_11'), + "placed_at < delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_11"), ), sa.CheckConstraint( - 'placed_at < dispatch_at', - name=op.f('ck_orders_on_ordered_timestamps_5'), + "placed_at < dispatch_at", + name=op.f("ck_orders_on_ordered_timestamps_5"), ), sa.CheckConstraint( - 'placed_at < first_estimated_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_1'), + "placed_at < first_estimated_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_1"), ), sa.CheckConstraint( - 'placed_at < left_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_9'), + "placed_at < left_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_9"), ), sa.CheckConstraint( - 'placed_at < reached_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_10'), + "placed_at < reached_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_10"), ), sa.CheckConstraint( - 'placed_at < reached_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_8'), + "placed_at < reached_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_8"), ), sa.CheckConstraint( - 'placed_at < restaurant_confirmed_at', - name=op.f('ck_orders_on_ordered_timestamps_4'), + "placed_at < restaurant_confirmed_at", + name=op.f("ck_orders_on_ordered_timestamps_4"), ), sa.CheckConstraint( - 'placed_at < restaurant_notified_at', - name=op.f('ck_orders_on_ordered_timestamps_3'), + "placed_at < restaurant_notified_at", + name=op.f("ck_orders_on_ordered_timestamps_3"), ), sa.CheckConstraint( - 'placed_at < scheduled_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_0'), + "placed_at < scheduled_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_0"), ), sa.CheckConstraint( - 'reached_delivery_at < delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_52'), + "reached_delivery_at < delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_52"), ), sa.CheckConstraint( - 'reached_pickup_at < delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_46'), + "reached_pickup_at < delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_46"), ), sa.CheckConstraint( - 'reached_pickup_at < left_pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_44'), + "reached_pickup_at < left_pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_44"), ), sa.CheckConstraint( - 'reached_pickup_at < pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_43'), + "reached_pickup_at < pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_43"), ), sa.CheckConstraint( - 'reached_pickup_at < reached_delivery_at', - name=op.f('ck_orders_on_ordered_timestamps_45'), + "reached_pickup_at < reached_delivery_at", + name=op.f("ck_orders_on_ordered_timestamps_45"), ), sa.CheckConstraint( - 'restaurant_confirmed_at < pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_24'), + "restaurant_confirmed_at < pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_24"), ), sa.CheckConstraint( - 'restaurant_notified_at < pickup_at', - name=op.f('ck_orders_on_ordered_timestamps_23'), + "restaurant_notified_at < pickup_at", + name=op.f("ck_orders_on_ordered_timestamps_23"), ), sa.CheckConstraint( - 'restaurant_notified_at < restaurant_confirmed_at', - name=op.f('ck_orders_on_ordered_timestamps_22'), + "restaurant_notified_at < restaurant_confirmed_at", + name=op.f("ck_orders_on_ordered_timestamps_22"), ), sa.CheckConstraint( - '(pickup_at IS NULL AND pickup_not_confirmed IS NULL) OR (pickup_at IS NOT NULL AND pickup_not_confirmed IS NOT NULL)', # noqa:E501 - name=op.f('pickup_not_confirmed_only_if_pickup'), + "(pickup_at IS NULL AND pickup_not_confirmed IS NULL) OR (pickup_at IS NOT NULL AND pickup_not_confirmed IS NOT NULL)", # noqa:E501 + name=op.f("pickup_not_confirmed_only_if_pickup"), ), sa.CheckConstraint( - '(delivery_at IS NULL AND delivery_not_confirmed IS NULL) OR (delivery_at IS NOT NULL AND delivery_not_confirmed IS NOT NULL)', # noqa:E501 - name=op.f('delivery_not_confirmed_only_if_delivery'), + "(delivery_at IS NULL AND delivery_not_confirmed IS NULL) OR (delivery_at IS NOT NULL AND delivery_not_confirmed IS NOT NULL)", # noqa:E501 + name=op.f("delivery_not_confirmed_only_if_delivery"), ), sa.CheckConstraint( - '(delivery_at IS NULL AND courier_waited_at_delivery IS NULL) OR (delivery_at IS NOT NULL AND courier_waited_at_delivery IS NOT NULL)', # noqa:E501 - name=op.f('courier_waited_at_delivery_only_if_delivery'), + "(delivery_at IS NULL AND courier_waited_at_delivery IS NULL) OR (delivery_at IS NOT NULL AND courier_waited_at_delivery IS NOT NULL)", # noqa:E501 + name=op.f("courier_waited_at_delivery_only_if_delivery"), ), sa.ForeignKeyConstraint( - ['courier_id'], - [f'{config.CLEAN_SCHEMA}.couriers.id'], - name=op.f('fk_orders_to_couriers_via_courier_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["courier_id"], + [f"{config.CLEAN_SCHEMA}.couriers.id"], + name=op.f("fk_orders_to_couriers_via_courier_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['customer_id'], - [f'{config.CLEAN_SCHEMA}.customers.id'], - name=op.f('fk_orders_to_customers_via_customer_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["customer_id"], + [f"{config.CLEAN_SCHEMA}.customers.id"], + name=op.f("fk_orders_to_customers_via_customer_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['delivery_address_id'], - [f'{config.CLEAN_SCHEMA}.addresses.id'], - name=op.f('fk_orders_to_addresses_via_delivery_address_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["delivery_address_id"], + [f"{config.CLEAN_SCHEMA}.addresses.id"], + name=op.f("fk_orders_to_addresses_via_delivery_address_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['pickup_address_id'], - [f'{config.CLEAN_SCHEMA}.addresses.id'], - name=op.f('fk_orders_to_addresses_via_pickup_address_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["pickup_address_id"], + [f"{config.CLEAN_SCHEMA}.addresses.id"], + name=op.f("fk_orders_to_addresses_via_pickup_address_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['restaurant_id'], - [f'{config.CLEAN_SCHEMA}.restaurants.id'], - name=op.f('fk_orders_to_restaurants_via_restaurant_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["restaurant_id"], + [f"{config.CLEAN_SCHEMA}.restaurants.id"], + name=op.f("fk_orders_to_restaurants_via_restaurant_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), - sa.PrimaryKeyConstraint('id', name=op.f('pk_orders')), + sa.PrimaryKeyConstraint("id", name=op.f("pk_orders")), *( [ sa.ForeignKeyConstraint( - ['id'], - [f'{config.ORIGINAL_SCHEMA}.orders.id'], - name=op.f('pk_orders_sanity'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["id"], + [f"{config.ORIGINAL_SCHEMA}.orders.id"], + name=op.f("pk_orders_sanity"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['delivery_id'], - [f'{config.ORIGINAL_SCHEMA}.deliveries.id'], - name=op.f('pk_deliveries_sanity'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["delivery_id"], + [f"{config.ORIGINAL_SCHEMA}.deliveries.id"], + name=op.f("pk_deliveries_sanity"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), ] if not config.TESTING @@ -650,156 +650,156 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_cancelled'), - 'orders', - ['cancelled'], + op.f("ix_orders_on_cancelled"), + "orders", + ["cancelled"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_cancelled_at_corrected'), - 'orders', - ['cancelled_at_corrected'], + op.f("ix_orders_on_cancelled_at_corrected"), + "orders", + ["cancelled_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_courier_accepted_at_corrected'), - 'orders', - ['courier_accepted_at_corrected'], + op.f("ix_orders_on_courier_accepted_at_corrected"), + "orders", + ["courier_accepted_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_courier_id'), - 'orders', - ['courier_id'], + op.f("ix_orders_on_courier_id"), + "orders", + ["courier_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_courier_notified_at_corrected'), - 'orders', - ['courier_notified_at_corrected'], + op.f("ix_orders_on_courier_notified_at_corrected"), + "orders", + ["courier_notified_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_customer_id'), - 'orders', - ['customer_id'], + op.f("ix_orders_on_customer_id"), + "orders", + ["customer_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_delivery_address_id'), - 'orders', - ['delivery_address_id'], + op.f("ix_orders_on_delivery_address_id"), + "orders", + ["delivery_address_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_delivery_at_corrected'), - 'orders', - ['delivery_at_corrected'], + op.f("ix_orders_on_delivery_at_corrected"), + "orders", + ["delivery_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_delivery_id'), - 'orders', - ['delivery_id'], + op.f("ix_orders_on_delivery_id"), + "orders", + ["delivery_id"], unique=True, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_dispatch_at_corrected'), - 'orders', - ['dispatch_at_corrected'], + op.f("ix_orders_on_dispatch_at_corrected"), + "orders", + ["dispatch_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_estimated_prep_buffer'), - 'orders', - ['estimated_prep_buffer'], + op.f("ix_orders_on_estimated_prep_buffer"), + "orders", + ["estimated_prep_buffer"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_estimated_prep_duration'), - 'orders', - ['estimated_prep_duration'], + op.f("ix_orders_on_estimated_prep_duration"), + "orders", + ["estimated_prep_duration"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_estimated_prep_duration_corrected'), - 'orders', - ['estimated_prep_duration_corrected'], + op.f("ix_orders_on_estimated_prep_duration_corrected"), + "orders", + ["estimated_prep_duration_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_left_pickup_at_corrected'), - 'orders', - ['left_pickup_at_corrected'], + op.f("ix_orders_on_left_pickup_at_corrected"), + "orders", + ["left_pickup_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_pickup_address_id'), - 'orders', - ['pickup_address_id'], + op.f("ix_orders_on_pickup_address_id"), + "orders", + ["pickup_address_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_pickup_at_corrected'), - 'orders', - ['pickup_at_corrected'], + op.f("ix_orders_on_pickup_at_corrected"), + "orders", + ["pickup_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_placed_at'), - 'orders', - ['placed_at'], + op.f("ix_orders_on_placed_at"), + "orders", + ["placed_at"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_restaurant_confirmed_at_corrected'), - 'orders', - ['restaurant_confirmed_at_corrected'], + op.f("ix_orders_on_restaurant_confirmed_at_corrected"), + "orders", + ["restaurant_confirmed_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_restaurant_id'), - 'orders', - ['restaurant_id'], + op.f("ix_orders_on_restaurant_id"), + "orders", + ["restaurant_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_restaurant_notified_at_corrected'), - 'orders', - ['restaurant_notified_at_corrected'], + op.f("ix_orders_on_restaurant_notified_at_corrected"), + "orders", + ["restaurant_notified_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_scheduled_delivery_at'), - 'orders', - ['scheduled_delivery_at'], + op.f("ix_orders_on_scheduled_delivery_at"), + "orders", + ["scheduled_delivery_at"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_orders_on_scheduled_delivery_at_corrected'), - 'orders', - ['scheduled_delivery_at_corrected'], + op.f("ix_orders_on_scheduled_delivery_at_corrected"), + "orders", + ["scheduled_delivery_at_corrected"], unique=False, schema=config.CLEAN_SCHEMA, ) @@ -807,4 +807,4 @@ def upgrade(): def downgrade(): """Downgrade to revision None.""" - op.execute(f'DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;') + op.execute(f"DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;") diff --git a/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py b/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py index ac6df40..b0fa779 100644 --- a/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py +++ b/migrations/versions/rev_20210102_18_888e352d7526_add_pixel_grid.py @@ -12,141 +12,141 @@ from alembic import op from velofy import configuration -revision = '888e352d7526' -down_revision = 'f11cd76d2f45' +revision = "888e352d7526" +down_revision = "f11cd76d2f45" branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): """Upgrade to revision 888e352d7526.""" op.create_table( - 'grids', - sa.Column('id', sa.SmallInteger(), autoincrement=True, nullable=False), - sa.Column('city_id', sa.SmallInteger(), nullable=False), - sa.Column('side_length', sa.SmallInteger(), nullable=True), - sa.PrimaryKeyConstraint('id', name=op.f('pk_grids')), + "grids", + sa.Column("id", sa.SmallInteger(), autoincrement=True, nullable=False), + sa.Column("city_id", sa.SmallInteger(), nullable=False), + sa.Column("side_length", sa.SmallInteger(), nullable=True), + sa.PrimaryKeyConstraint("id", name=op.f("pk_grids")), sa.ForeignKeyConstraint( - ['city_id'], - [f'{config.CLEAN_SCHEMA}.cities.id'], - name=op.f('fk_grids_to_cities_via_city_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["city_id"], + [f"{config.CLEAN_SCHEMA}.cities.id"], + name=op.f("fk_grids_to_cities_via_city_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.UniqueConstraint( - 'city_id', - 'side_length', - name=op.f('uq_grids_on_city_id_side_length'), + "city_id", + "side_length", + name=op.f("uq_grids_on_city_id_side_length"), ), # This `UniqueConstraint` is needed by the `addresses_pixels` table below. - sa.UniqueConstraint('id', 'city_id', name=op.f('uq_grids_on_id_city_id')), + sa.UniqueConstraint("id", "city_id", name=op.f("uq_grids_on_id_city_id")), schema=config.CLEAN_SCHEMA, ) op.create_table( - 'pixels', - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('grid_id', sa.SmallInteger(), nullable=False), - sa.Column('n_x', sa.SmallInteger(), nullable=False), - sa.Column('n_y', sa.SmallInteger(), nullable=False), - sa.CheckConstraint('0 <= n_x', name=op.f('ck_pixels_on_n_x_is_positive')), - sa.CheckConstraint('0 <= n_y', name=op.f('ck_pixels_on_n_y_is_positive')), + "pixels", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("grid_id", sa.SmallInteger(), nullable=False), + sa.Column("n_x", sa.SmallInteger(), nullable=False), + sa.Column("n_y", sa.SmallInteger(), nullable=False), + sa.CheckConstraint("0 <= n_x", name=op.f("ck_pixels_on_n_x_is_positive")), + sa.CheckConstraint("0 <= n_y", name=op.f("ck_pixels_on_n_y_is_positive")), sa.ForeignKeyConstraint( - ['grid_id'], - [f'{config.CLEAN_SCHEMA}.grids.id'], - name=op.f('fk_pixels_to_grids_via_grid_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["grid_id"], + [f"{config.CLEAN_SCHEMA}.grids.id"], + name=op.f("fk_pixels_to_grids_via_grid_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), - sa.PrimaryKeyConstraint('id', name=op.f('pk_pixels')), + sa.PrimaryKeyConstraint("id", name=op.f("pk_pixels")), sa.UniqueConstraint( - 'grid_id', - 'n_x', - 'n_y', - name=op.f('uq_pixels_on_grid_id_n_x_n_y'), + "grid_id", + "n_x", + "n_y", + name=op.f("uq_pixels_on_grid_id_n_x_n_y"), ), - sa.UniqueConstraint('id', 'grid_id', name=op.f('uq_pixels_on_id_grid_id')), + sa.UniqueConstraint("id", "grid_id", name=op.f("uq_pixels_on_id_grid_id")), schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_pixels_on_grid_id'), - 'pixels', - ['grid_id'], + op.f("ix_pixels_on_grid_id"), + "pixels", + ["grid_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_pixels_on_n_x'), - 'pixels', - ['n_x'], + op.f("ix_pixels_on_n_x"), + "pixels", + ["n_x"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_pixels_on_n_y'), - 'pixels', - ['n_y'], + op.f("ix_pixels_on_n_y"), + "pixels", + ["n_y"], unique=False, schema=config.CLEAN_SCHEMA, ) # This `UniqueConstraint` is needed by the `addresses_pixels` table below. op.create_unique_constraint( - 'uq_addresses_on_id_city_id', - 'addresses', - ['id', 'city_id'], + "uq_addresses_on_id_city_id", + "addresses", + ["id", "city_id"], schema=config.CLEAN_SCHEMA, ) op.create_table( - 'addresses_pixels', - sa.Column('address_id', sa.Integer(), nullable=False), - sa.Column('city_id', sa.SmallInteger(), nullable=False), - sa.Column('grid_id', sa.SmallInteger(), nullable=False), - sa.Column('pixel_id', sa.Integer(), nullable=False), + "addresses_pixels", + sa.Column("address_id", sa.Integer(), nullable=False), + sa.Column("city_id", sa.SmallInteger(), nullable=False), + sa.Column("grid_id", sa.SmallInteger(), nullable=False), + sa.Column("pixel_id", sa.Integer(), nullable=False), sa.ForeignKeyConstraint( - ['address_id', 'city_id'], + ["address_id", "city_id"], [ - f'{config.CLEAN_SCHEMA}.addresses.id', - f'{config.CLEAN_SCHEMA}.addresses.city_id', + f"{config.CLEAN_SCHEMA}.addresses.id", + f"{config.CLEAN_SCHEMA}.addresses.city_id", ], - name=op.f('fk_addresses_pixels_to_addresses_via_address_id_city_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + name=op.f("fk_addresses_pixels_to_addresses_via_address_id_city_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['grid_id', 'city_id'], + ["grid_id", "city_id"], [ - f'{config.CLEAN_SCHEMA}.grids.id', - f'{config.CLEAN_SCHEMA}.grids.city_id', + f"{config.CLEAN_SCHEMA}.grids.id", + f"{config.CLEAN_SCHEMA}.grids.city_id", ], - name=op.f('fk_addresses_pixels_to_grids_via_grid_id_city_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + name=op.f("fk_addresses_pixels_to_grids_via_grid_id_city_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['pixel_id', 'grid_id'], + ["pixel_id", "grid_id"], [ - f'{config.CLEAN_SCHEMA}.pixels.id', - f'{config.CLEAN_SCHEMA}.pixels.grid_id', + f"{config.CLEAN_SCHEMA}.pixels.id", + f"{config.CLEAN_SCHEMA}.pixels.grid_id", ], - name=op.f('fk_addresses_pixels_to_pixels_via_pixel_id_grid_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + name=op.f("fk_addresses_pixels_to_pixels_via_pixel_id_grid_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.PrimaryKeyConstraint( - 'address_id', - 'pixel_id', - name=op.f('pk_addresses_pixels'), + "address_id", + "pixel_id", + name=op.f("pk_addresses_pixels"), ), sa.UniqueConstraint( - 'address_id', - 'grid_id', - name=op.f('uq_addresses_pixels_on_address_id_grid_id'), + "address_id", + "grid_id", + name=op.f("uq_addresses_pixels_on_address_id_grid_id"), ), schema=config.CLEAN_SCHEMA, ) @@ -154,27 +154,27 @@ def upgrade(): def downgrade(): """Downgrade to revision f11cd76d2f45.""" - op.drop_table('addresses_pixels', schema=config.CLEAN_SCHEMA) + op.drop_table("addresses_pixels", schema=config.CLEAN_SCHEMA) op.drop_constraint( - 'uq_addresses_on_id_city_id', - 'addresses', + "uq_addresses_on_id_city_id", + "addresses", type_=None, schema=config.CLEAN_SCHEMA, ) op.drop_index( - op.f('ix_pixels_on_n_y'), - table_name='pixels', + op.f("ix_pixels_on_n_y"), + table_name="pixels", schema=config.CLEAN_SCHEMA, ) op.drop_index( - op.f('ix_pixels_on_n_x'), - table_name='pixels', + op.f("ix_pixels_on_n_x"), + table_name="pixels", schema=config.CLEAN_SCHEMA, ) op.drop_index( - op.f('ix_pixels_on_grid_id'), - table_name='pixels', + op.f("ix_pixels_on_grid_id"), + table_name="pixels", schema=config.CLEAN_SCHEMA, ) - op.drop_table('pixels', schema=config.CLEAN_SCHEMA) - op.drop_table('grids', schema=config.CLEAN_SCHEMA) + op.drop_table("pixels", schema=config.CLEAN_SCHEMA) + op.drop_table("grids", schema=config.CLEAN_SCHEMA) diff --git a/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py b/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py index 980f370..71b353b 100644 --- a/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py +++ b/migrations/versions/rev_20210106_19_e40623e10405_add_demand_forecasting.py @@ -13,33 +13,33 @@ from sqlalchemy.dialects import postgresql from velofy import configuration -revision = 'e40623e10405' -down_revision = '888e352d7526' +revision = "e40623e10405" +down_revision = "888e352d7526" branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): """Upgrade to revision e40623e10405.""" op.create_table( - 'forecasts', - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('pixel_id', sa.Integer(), nullable=False), - sa.Column('start_at', sa.DateTime(), nullable=False), - sa.Column('time_step', sa.SmallInteger(), nullable=False), - sa.Column('training_horizon', sa.SmallInteger(), nullable=False), - sa.Column('method', sa.Unicode(length=20), nullable=False), - sa.Column('prediction', postgresql.DOUBLE_PRECISION(), nullable=False), - sa.PrimaryKeyConstraint('id', name=op.f('pk_forecasts')), + "forecasts", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("pixel_id", sa.Integer(), nullable=False), + sa.Column("start_at", sa.DateTime(), nullable=False), + sa.Column("time_step", sa.SmallInteger(), nullable=False), + sa.Column("training_horizon", sa.SmallInteger(), nullable=False), + sa.Column("method", sa.Unicode(length=20), nullable=False), + sa.Column("prediction", postgresql.DOUBLE_PRECISION(), nullable=False), + sa.PrimaryKeyConstraint("id", name=op.f("pk_forecasts")), sa.ForeignKeyConstraint( - ['pixel_id'], - [f'{config.CLEAN_SCHEMA}.pixels.id'], - name=op.f('fk_forecasts_to_pixels_via_pixel_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["pixel_id"], + [f"{config.CLEAN_SCHEMA}.pixels.id"], + name=op.f("fk_forecasts_to_pixels_via_pixel_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.CheckConstraint( """ @@ -49,44 +49,44 @@ def upgrade(): EXTRACT(HOUR FROM start_at) > 22 ) """, - name=op.f('ck_forecasts_on_start_at_must_be_within_operating_hours'), + name=op.f("ck_forecasts_on_start_at_must_be_within_operating_hours"), ), sa.CheckConstraint( - 'CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0', - name=op.f('ck_forecasts_on_start_at_minutes_must_be_quarters_of_the_hour'), + "CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0", + name=op.f("ck_forecasts_on_start_at_minutes_must_be_quarters_of_the_hour"), ), sa.CheckConstraint( - 'CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0', - name=op.f('ck_forecasts_on_start_at_allows_no_microseconds'), + "CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0", + name=op.f("ck_forecasts_on_start_at_allows_no_microseconds"), ), sa.CheckConstraint( - 'EXTRACT(SECONDS FROM start_at) = 0', - name=op.f('ck_forecasts_on_start_at_allows_no_seconds'), + "EXTRACT(SECONDS FROM start_at) = 0", + name=op.f("ck_forecasts_on_start_at_allows_no_seconds"), ), sa.CheckConstraint( - 'time_step > 0', - name=op.f('ck_forecasts_on_time_step_must_be_positive'), + "time_step > 0", + name=op.f("ck_forecasts_on_time_step_must_be_positive"), ), sa.CheckConstraint( - 'training_horizon > 0', - name=op.f('ck_forecasts_on_training_horizon_must_be_positive'), + "training_horizon > 0", + name=op.f("ck_forecasts_on_training_horizon_must_be_positive"), ), sa.UniqueConstraint( - 'pixel_id', - 'start_at', - 'time_step', - 'training_horizon', - 'method', + "pixel_id", + "start_at", + "time_step", + "training_horizon", + "method", name=op.f( - 'uq_forecasts_on_pixel_id_start_at_time_step_training_horizon_method', + "uq_forecasts_on_pixel_id_start_at_time_step_training_horizon_method", ), ), schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_forecasts_on_pixel_id'), - 'forecasts', - ['pixel_id'], + op.f("ix_forecasts_on_pixel_id"), + "forecasts", + ["pixel_id"], unique=False, schema=config.CLEAN_SCHEMA, ) @@ -94,4 +94,4 @@ def upgrade(): def downgrade(): """Downgrade to revision 888e352d7526.""" - op.drop_table('forecasts', schema=config.CLEAN_SCHEMA) + op.drop_table("forecasts", schema=config.CLEAN_SCHEMA) diff --git a/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py b/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py index aff868d..5a85485 100644 --- a/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py +++ b/migrations/versions/rev_20210120_16_26711cd3f9b9_add_confidence_intervals_to_forecasts.py @@ -13,46 +13,46 @@ from sqlalchemy.dialects import postgresql from velofy import configuration -revision = '26711cd3f9b9' -down_revision = 'e40623e10405' +revision = "26711cd3f9b9" +down_revision = "e40623e10405" branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): """Upgrade to revision 26711cd3f9b9.""" op.alter_column( - 'forecasts', - 'method', - new_column_name='model', + "forecasts", + "method", + new_column_name="model", schema=config.CLEAN_SCHEMA, ) op.add_column( - 'forecasts', - sa.Column('low80', postgresql.DOUBLE_PRECISION(), nullable=True), + "forecasts", + sa.Column("low80", postgresql.DOUBLE_PRECISION(), nullable=True), schema=config.CLEAN_SCHEMA, ) op.add_column( - 'forecasts', - sa.Column('high80', postgresql.DOUBLE_PRECISION(), nullable=True), + "forecasts", + sa.Column("high80", postgresql.DOUBLE_PRECISION(), nullable=True), schema=config.CLEAN_SCHEMA, ) op.add_column( - 'forecasts', - sa.Column('low95', postgresql.DOUBLE_PRECISION(), nullable=True), + "forecasts", + sa.Column("low95", postgresql.DOUBLE_PRECISION(), nullable=True), schema=config.CLEAN_SCHEMA, ) op.add_column( - 'forecasts', - sa.Column('high95', postgresql.DOUBLE_PRECISION(), nullable=True), + "forecasts", + sa.Column("high95", postgresql.DOUBLE_PRECISION(), nullable=True), schema=config.CLEAN_SCHEMA, ) op.create_check_constraint( - op.f('ck_forecasts_on_ci_upper_and_lower_bounds'), - 'forecasts', + op.f("ck_forecasts_on_ci_upper_and_lower_bounds"), + "forecasts", """ NOT ( low80 IS NULL AND high80 IS NOT NULL @@ -67,8 +67,8 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) op.create_check_constraint( - op.f('prediction_must_be_within_ci'), - 'forecasts', + op.f("prediction_must_be_within_ci"), + "forecasts", """ NOT ( prediction < low80 @@ -83,8 +83,8 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) op.create_check_constraint( - op.f('ci_upper_bound_greater_than_lower_bound'), - 'forecasts', + op.f("ci_upper_bound_greater_than_lower_bound"), + "forecasts", """ NOT ( low80 > high80 @@ -95,8 +95,8 @@ def upgrade(): schema=config.CLEAN_SCHEMA, ) op.create_check_constraint( - op.f('ci95_must_be_wider_than_ci80'), - 'forecasts', + op.f("ci95_must_be_wider_than_ci80"), + "forecasts", """ NOT ( low80 < low95 @@ -111,28 +111,28 @@ def upgrade(): def downgrade(): """Downgrade to revision e40623e10405.""" op.alter_column( - 'forecasts', - 'model', - new_column_name='method', + "forecasts", + "model", + new_column_name="method", schema=config.CLEAN_SCHEMA, ) op.drop_column( - 'forecasts', - 'low80', + "forecasts", + "low80", schema=config.CLEAN_SCHEMA, ) op.drop_column( - 'forecasts', - 'high80', + "forecasts", + "high80", schema=config.CLEAN_SCHEMA, ) op.drop_column( - 'forecasts', - 'low95', + "forecasts", + "low95", schema=config.CLEAN_SCHEMA, ) op.drop_column( - 'forecasts', - 'high95', + "forecasts", + "high95", schema=config.CLEAN_SCHEMA, ) diff --git a/migrations/versions/rev_20210123_15_e86290e7305e_remove_orders_from_restaurants_with.py b/migrations/versions/rev_20210123_15_e86290e7305e_remove_orders_from_restaurants_with.py index e276723..088fc4b 100644 --- a/migrations/versions/rev_20210123_15_e86290e7305e_remove_orders_from_restaurants_with.py +++ b/migrations/versions/rev_20210123_15_e86290e7305e_remove_orders_from_restaurants_with.py @@ -129,13 +129,13 @@ from alembic import op from velofy import configuration -revision = 'e86290e7305e' -down_revision = '26711cd3f9b9' +revision = "e86290e7305e" +down_revision = "26711cd3f9b9" branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): @@ -347,26 +347,26 @@ def upgrade(): """, ) op.create_unique_constraint( - 'uq_restaurants_on_id_address_id', - 'restaurants', - ['id', 'address_id'], + "uq_restaurants_on_id_address_id", + "restaurants", + ["id", "address_id"], schema=config.CLEAN_SCHEMA, ) op.create_foreign_key( - op.f('fk_orders_to_restaurants_via_restaurant_id_pickup_address_id'), - 'orders', - 'restaurants', - ['restaurant_id', 'pickup_address_id'], - ['id', 'address_id'], + op.f("fk_orders_to_restaurants_via_restaurant_id_pickup_address_id"), + "orders", + "restaurants", + ["restaurant_id", "pickup_address_id"], + ["id", "address_id"], source_schema=config.CLEAN_SCHEMA, referent_schema=config.CLEAN_SCHEMA, - onupdate='RESTRICT', - ondelete='RESTRICT', + onupdate="RESTRICT", + ondelete="RESTRICT", ) op.drop_constraint( - 'fk_orders_to_restaurants_via_restaurant_id', - 'orders', - type_='foreignkey', + "fk_orders_to_restaurants_via_restaurant_id", + "orders", + type_="foreignkey", schema=config.CLEAN_SCHEMA, ) @@ -374,25 +374,25 @@ def upgrade(): def downgrade(): """Downgrade to revision 26711cd3f9b9.""" op.create_foreign_key( - op.f('fk_orders_to_restaurants_via_restaurant_id'), - 'orders', - 'restaurants', - ['restaurant_id'], - ['id'], + op.f("fk_orders_to_restaurants_via_restaurant_id"), + "orders", + "restaurants", + ["restaurant_id"], + ["id"], source_schema=config.CLEAN_SCHEMA, referent_schema=config.CLEAN_SCHEMA, - onupdate='RESTRICT', - ondelete='RESTRICT', + onupdate="RESTRICT", + ondelete="RESTRICT", ) op.drop_constraint( - 'fk_orders_to_restaurants_via_restaurant_id_pickup_address_id', - 'orders', - type_='foreignkey', + "fk_orders_to_restaurants_via_restaurant_id_pickup_address_id", + "orders", + type_="foreignkey", schema=config.CLEAN_SCHEMA, ) op.drop_constraint( - 'uq_restaurants_on_id_address_id', - 'restaurants', - type_='unique', + "uq_restaurants_on_id_address_id", + "restaurants", + type_="unique", schema=config.CLEAN_SCHEMA, ) diff --git a/migrations/versions/rev_20210129_11_c2af85bada01_store_actuals_with_forecast.py b/migrations/versions/rev_20210129_11_c2af85bada01_store_actuals_with_forecast.py index 6594993..fad7ddb 100644 --- a/migrations/versions/rev_20210129_11_c2af85bada01_store_actuals_with_forecast.py +++ b/migrations/versions/rev_20210129_11_c2af85bada01_store_actuals_with_forecast.py @@ -12,30 +12,30 @@ from alembic import op from velofy import configuration -revision = 'c2af85bada01' -down_revision = 'e86290e7305e' +revision = "c2af85bada01" +down_revision = "e86290e7305e" branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): """Upgrade to revision c2af85bada01.""" op.add_column( - 'forecasts', - sa.Column('actual', sa.SmallInteger(), nullable=False), + "forecasts", + sa.Column("actual", sa.SmallInteger(), nullable=False), schema=config.CLEAN_SCHEMA, ) op.create_check_constraint( - op.f('ck_forecasts_on_actuals_must_be_non_negative'), - 'forecasts', - 'actual >= 0', + op.f("ck_forecasts_on_actuals_must_be_non_negative"), + "forecasts", + "actual >= 0", schema=config.CLEAN_SCHEMA, ) def downgrade(): """Downgrade to revision e86290e7305e.""" - op.drop_column('forecasts', 'actual', schema=config.CLEAN_SCHEMA) + op.drop_column("forecasts", "actual", schema=config.CLEAN_SCHEMA) diff --git a/migrations/versions/rev_20210202_12_8bfb928a31f8_rename_training_horizon_into_train_horizon.py b/migrations/versions/rev_20210202_12_8bfb928a31f8_rename_training_horizon_into_train_horizon.py index a060a88..72fb236 100644 --- a/migrations/versions/rev_20210202_12_8bfb928a31f8_rename_training_horizon_into_train_horizon.py +++ b/migrations/versions/rev_20210202_12_8bfb928a31f8_rename_training_horizon_into_train_horizon.py @@ -11,13 +11,13 @@ from alembic import op from velofy import configuration -revision = '8bfb928a31f8' -down_revision = 'c2af85bada01' +revision = "8bfb928a31f8" +down_revision = "c2af85bada01" branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): diff --git a/migrations/versions/rev_20210301_16_b4dd0b8903a5_add_distance_matrix.py b/migrations/versions/rev_20210301_16_b4dd0b8903a5_add_distance_matrix.py index 01bb5c9..a99d55e 100644 --- a/migrations/versions/rev_20210301_16_b4dd0b8903a5_add_distance_matrix.py +++ b/migrations/versions/rev_20210301_16_b4dd0b8903a5_add_distance_matrix.py @@ -13,79 +13,79 @@ from sqlalchemy.dialects import postgresql from velofy import configuration -revision = 'b4dd0b8903a5' -down_revision = '8bfb928a31f8' +revision = "b4dd0b8903a5" +down_revision = "8bfb928a31f8" branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): """Upgrade to revision b4dd0b8903a5.""" op.create_table( - 'addresses_addresses', - sa.Column('first_address_id', sa.Integer(), nullable=False), - sa.Column('second_address_id', sa.Integer(), nullable=False), - sa.Column('city_id', sa.SmallInteger(), nullable=False), - sa.Column('air_distance', sa.Integer(), nullable=False), - sa.Column('bicycle_distance', sa.Integer(), nullable=True), - sa.Column('bicycle_duration', sa.Integer(), nullable=True), - sa.Column('directions', postgresql.JSON(), nullable=True), + "addresses_addresses", + sa.Column("first_address_id", sa.Integer(), nullable=False), + sa.Column("second_address_id", sa.Integer(), nullable=False), + sa.Column("city_id", sa.SmallInteger(), nullable=False), + sa.Column("air_distance", sa.Integer(), nullable=False), + sa.Column("bicycle_distance", sa.Integer(), nullable=True), + sa.Column("bicycle_duration", sa.Integer(), nullable=True), + sa.Column("directions", postgresql.JSON(), nullable=True), sa.PrimaryKeyConstraint( - 'first_address_id', - 'second_address_id', - name=op.f('pk_addresses_addresses'), + "first_address_id", + "second_address_id", + name=op.f("pk_addresses_addresses"), ), sa.ForeignKeyConstraint( - ['first_address_id', 'city_id'], + ["first_address_id", "city_id"], [ - f'{config.CLEAN_SCHEMA}.addresses.id', - f'{config.CLEAN_SCHEMA}.addresses.city_id', + f"{config.CLEAN_SCHEMA}.addresses.id", + f"{config.CLEAN_SCHEMA}.addresses.city_id", ], name=op.f( - 'fk_addresses_addresses_to_addresses_via_first_address_id_city_id', + "fk_addresses_addresses_to_addresses_via_first_address_id_city_id", ), - onupdate='RESTRICT', - ondelete='RESTRICT', + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['second_address_id', 'city_id'], + ["second_address_id", "city_id"], [ - f'{config.CLEAN_SCHEMA}.addresses.id', - f'{config.CLEAN_SCHEMA}.addresses.city_id', + f"{config.CLEAN_SCHEMA}.addresses.id", + f"{config.CLEAN_SCHEMA}.addresses.city_id", ], name=op.f( - 'fk_addresses_addresses_to_addresses_via_second_address_id_city_id', + "fk_addresses_addresses_to_addresses_via_second_address_id_city_id", ), - onupdate='RESTRICT', - ondelete='RESTRICT', + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.UniqueConstraint( - 'first_address_id', - 'second_address_id', - name=op.f('uq_addresses_addresses_on_first_address_id_second_address_id'), + "first_address_id", + "second_address_id", + name=op.f("uq_addresses_addresses_on_first_address_id_second_address_id"), ), sa.CheckConstraint( - 'first_address_id < second_address_id', - name=op.f('ck_addresses_addresses_on_distances_are_symmetric_for_bicycles'), + "first_address_id < second_address_id", + name=op.f("ck_addresses_addresses_on_distances_are_symmetric_for_bicycles"), ), sa.CheckConstraint( - '0 <= air_distance AND air_distance < 20000', - name=op.f('ck_addresses_addresses_on_realistic_air_distance'), + "0 <= air_distance AND air_distance < 20000", + name=op.f("ck_addresses_addresses_on_realistic_air_distance"), ), sa.CheckConstraint( - 'bicycle_distance < 25000', - name=op.f('ck_addresses_addresses_on_realistic_bicycle_distance'), + "bicycle_distance < 25000", + name=op.f("ck_addresses_addresses_on_realistic_bicycle_distance"), ), sa.CheckConstraint( - 'air_distance <= bicycle_distance', - name=op.f('ck_addresses_addresses_on_air_distance_is_shortest'), + "air_distance <= bicycle_distance", + name=op.f("ck_addresses_addresses_on_air_distance_is_shortest"), ), sa.CheckConstraint( - '0 <= bicycle_duration AND bicycle_duration <= 3600', - name=op.f('ck_addresses_addresses_on_realistic_bicycle_travel_time'), + "0 <= bicycle_duration AND bicycle_duration <= 3600", + name=op.f("ck_addresses_addresses_on_realistic_bicycle_travel_time"), ), schema=config.CLEAN_SCHEMA, ) @@ -93,4 +93,4 @@ def upgrade(): def downgrade(): """Downgrade to revision 8bfb928a31f8.""" - op.drop_table('addresses_addresses', schema=config.CLEAN_SCHEMA) + op.drop_table("addresses_addresses", schema=config.CLEAN_SCHEMA) diff --git a/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py b/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py index d448e9f..0b49adf 100644 --- a/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py +++ b/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py @@ -12,13 +12,13 @@ from alembic import op from velofy import configuration -revision = '81aa304d7a6e' -down_revision = 'b4dd0b8903a5' +revision = "81aa304d7a6e" +down_revision = "b4dd0b8903a5" branch_labels = None depends_on = None -config = configuration.make_config('testing' if os.getenv('TESTING') else 'production') +config = configuration.make_config("testing" if os.getenv("TESTING") else "production") def upgrade(): @@ -59,88 +59,88 @@ def upgrade(): # This `UniqueConstraint` is needed by the `replayed_orders` table below. op.create_unique_constraint( - 'uq_orders_on_id_ad_hoc', - 'orders', - ['id', 'ad_hoc'], + "uq_orders_on_id_ad_hoc", + "orders", + ["id", "ad_hoc"], schema=config.CLEAN_SCHEMA, ) op.create_table( - 'replay_simulations', - sa.Column('id', sa.Integer, autoincrement=True), - sa.Column('city_id', sa.SmallInteger, nullable=False), - sa.Column('strategy', sa.Unicode(length=100), nullable=False), - sa.Column('run', sa.SmallInteger, nullable=False), - sa.PrimaryKeyConstraint('id', name=op.f('pk_replay_simulations')), + "replay_simulations", + sa.Column("id", sa.Integer, autoincrement=True), + sa.Column("city_id", sa.SmallInteger, nullable=False), + sa.Column("strategy", sa.Unicode(length=100), nullable=False), + sa.Column("run", sa.SmallInteger, nullable=False), + sa.PrimaryKeyConstraint("id", name=op.f("pk_replay_simulations")), sa.ForeignKeyConstraint( - ['city_id'], - [f'{config.CLEAN_SCHEMA}.cities.id'], - name=op.f('fk_replay_simulations_to_cities_via_city_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["city_id"], + [f"{config.CLEAN_SCHEMA}.cities.id"], + name=op.f("fk_replay_simulations_to_cities_via_city_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.UniqueConstraint( - 'city_id', - 'strategy', - 'run', - name=op.f('uq_replay_simulations_on_city_id_strategy_run'), + "city_id", + "strategy", + "run", + name=op.f("uq_replay_simulations_on_city_id_strategy_run"), ), - sa.CheckConstraint('run >= 0', name=op.f('run_is_a_count')), + sa.CheckConstraint("run >= 0", name=op.f("run_is_a_count")), schema=config.CLEAN_SCHEMA, ) op.create_table( - 'replayed_orders', - sa.Column('simulation_id', sa.Integer, primary_key=True), - sa.Column('actual_order_id', sa.Integer, primary_key=True), - sa.Column('ad_hoc', sa.Boolean, nullable=False), - sa.Column('placed_at', sa.DateTime, nullable=False), - sa.Column('scheduled_delivery_at', sa.DateTime), - sa.Column('cancelled_at', sa.DateTime), - sa.Column('estimated_prep_duration', sa.SmallInteger), - sa.Column('restaurant_notified_at', sa.DateTime), - sa.Column('restaurant_confirmed_at', sa.DateTime), - sa.Column('restaurant_ready_at', sa.DateTime), - sa.Column('dispatch_at', sa.DateTime), - sa.Column('first_estimated_delivery_at', sa.DateTime), - sa.Column('courier_id', sa.Integer), - sa.Column('courier_notified_at', sa.DateTime), - sa.Column('courier_accepted_at', sa.DateTime), - sa.Column('utilization', sa.SmallInteger), - sa.Column('reached_pickup_at', sa.DateTime), - sa.Column('pickup_at', sa.DateTime), - sa.Column('left_pickup_at', sa.DateTime), - sa.Column('reached_delivery_at', sa.DateTime), - sa.Column('delivery_at', sa.DateTime), + "replayed_orders", + sa.Column("simulation_id", sa.Integer, primary_key=True), + sa.Column("actual_order_id", sa.Integer, primary_key=True), + sa.Column("ad_hoc", sa.Boolean, nullable=False), + sa.Column("placed_at", sa.DateTime, nullable=False), + sa.Column("scheduled_delivery_at", sa.DateTime), + sa.Column("cancelled_at", sa.DateTime), + sa.Column("estimated_prep_duration", sa.SmallInteger), + sa.Column("restaurant_notified_at", sa.DateTime), + sa.Column("restaurant_confirmed_at", sa.DateTime), + sa.Column("restaurant_ready_at", sa.DateTime), + sa.Column("dispatch_at", sa.DateTime), + sa.Column("first_estimated_delivery_at", sa.DateTime), + sa.Column("courier_id", sa.Integer), + sa.Column("courier_notified_at", sa.DateTime), + sa.Column("courier_accepted_at", sa.DateTime), + sa.Column("utilization", sa.SmallInteger), + sa.Column("reached_pickup_at", sa.DateTime), + sa.Column("pickup_at", sa.DateTime), + sa.Column("left_pickup_at", sa.DateTime), + sa.Column("reached_delivery_at", sa.DateTime), + sa.Column("delivery_at", sa.DateTime), sa.PrimaryKeyConstraint( - 'simulation_id', - 'actual_order_id', - name=op.f('pk_replayed_orders'), + "simulation_id", + "actual_order_id", + name=op.f("pk_replayed_orders"), ), sa.ForeignKeyConstraint( - ['simulation_id'], - [f'{config.CLEAN_SCHEMA}.replay_simulations.id'], - name=op.f('fk_replayed_orders_to_replay_simulations_via_simulation_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["simulation_id"], + [f"{config.CLEAN_SCHEMA}.replay_simulations.id"], + name=op.f("fk_replayed_orders_to_replay_simulations_via_simulation_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( # Needs the `UniqueConstraint` from above. - ['actual_order_id', 'ad_hoc'], + ["actual_order_id", "ad_hoc"], [ - f'{config.CLEAN_SCHEMA}.orders.id', - f'{config.CLEAN_SCHEMA}.orders.ad_hoc', + f"{config.CLEAN_SCHEMA}.orders.id", + f"{config.CLEAN_SCHEMA}.orders.ad_hoc", ], - name=op.f('fk_replayed_orders_to_orders_via_actual_order_id_ad_hoc'), - onupdate='RESTRICT', - ondelete='RESTRICT', + name=op.f("fk_replayed_orders_to_orders_via_actual_order_id_ad_hoc"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['courier_id'], - [f'{config.CLEAN_SCHEMA}.couriers.id'], - name=op.f('fk_replayed_orders_to_couriers_via_courier_id'), - onupdate='RESTRICT', - ondelete='RESTRICT', + ["courier_id"], + [f"{config.CLEAN_SCHEMA}.couriers.id"], + name=op.f("fk_replayed_orders_to_couriers_via_courier_id"), + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.CheckConstraint( """ @@ -156,7 +156,7 @@ def upgrade(): scheduled_delivery_at IS NOT NULL ) """, - name=op.f('either_ad_hoc_or_scheduled_order'), + name=op.f("either_ad_hoc_or_scheduled_order"), ), sa.CheckConstraint( """ @@ -169,7 +169,7 @@ def upgrade(): ) ) """, - name=op.f('ad_hoc_orders_within_business_hours'), + name=op.f("ad_hoc_orders_within_business_hours"), ), sa.CheckConstraint( """ @@ -190,7 +190,7 @@ def upgrade(): ) ) """, - name=op.f('scheduled_orders_within_business_hours'), + name=op.f("scheduled_orders_within_business_hours"), ), sa.CheckConstraint( """ @@ -204,7 +204,7 @@ def upgrade(): = 0 ) """, - name=op.f('scheduled_orders_must_be_at_quarters_of_an_hour'), + name=op.f("scheduled_orders_must_be_at_quarters_of_an_hour"), ), sa.CheckConstraint( """ @@ -212,7 +212,7 @@ def upgrade(): EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800 ) """, - name=op.f('scheduled_orders_not_within_30_minutes'), + name=op.f("scheduled_orders_not_within_30_minutes"), ), sa.CheckConstraint( """ @@ -244,7 +244,7 @@ def upgrade(): delivery_at IS NOT NULL ) """, - name=op.f('orders_must_be_either_cancelled_or_fully_simulated'), + name=op.f("orders_must_be_either_cancelled_or_fully_simulated"), ), sa.CheckConstraint( """ @@ -272,19 +272,19 @@ def upgrade(): delivery_at IS NOT NULL ) """, - name=op.f('cancellations_may_only_occur_before_pickup'), + name=op.f("cancellations_may_only_occur_before_pickup"), ), sa.CheckConstraint( - '0 <= estimated_prep_duration AND estimated_prep_duration <= 3600', - name=op.f('estimated_prep_duration_between_0_and_3600'), + "0 <= estimated_prep_duration AND estimated_prep_duration <= 3600", + name=op.f("estimated_prep_duration_between_0_and_3600"), ), sa.CheckConstraint( - 'estimated_prep_duration % 60 = 0', - name=op.f('estimated_prep_duration_must_be_whole_minutes'), + "estimated_prep_duration % 60 = 0", + name=op.f("estimated_prep_duration_must_be_whole_minutes"), ), sa.CheckConstraint( - '0 <= utilization AND utilization <= 100', - name=op.f('utilization_between_0_and_100'), + "0 <= utilization AND utilization <= 100", + name=op.f("utilization_between_0_and_100"), ), sa.CheckConstraint( """ @@ -294,71 +294,71 @@ def upgrade(): EXTRACT(HOUR FROM dispatch_at) < 11 ) """, - name=op.f('orders_dispatched_in_business_hours'), + name=op.f("orders_dispatched_in_business_hours"), ), *( sa.CheckConstraint( constraint, - name='ordered_timestamps_{index}'.format(index=index), + name="ordered_timestamps_{index}".format(index=index), ) for index, constraint in enumerate( ( - 'placed_at < scheduled_delivery_at', - 'placed_at < cancelled_at', - 'placed_at < restaurant_notified_at', - 'placed_at < restaurant_confirmed_at', - 'placed_at < restaurant_ready_at', - 'placed_at < dispatch_at', - 'placed_at < first_estimated_delivery_at', - 'placed_at < courier_notified_at', - 'placed_at < courier_accepted_at', - 'placed_at < reached_pickup_at', - 'placed_at < pickup_at', - 'placed_at < left_pickup_at', - 'placed_at < reached_delivery_at', - 'placed_at < delivery_at', - 'cancelled_at > restaurant_notified_at', - 'cancelled_at > restaurant_confirmed_at', - 'cancelled_at > restaurant_ready_at', - 'cancelled_at > dispatch_at', - 'cancelled_at > courier_notified_at', - 'cancelled_at > courier_accepted_at', - 'cancelled_at > reached_pickup_at', - 'restaurant_notified_at < restaurant_confirmed_at', - 'restaurant_notified_at < restaurant_ready_at', - 'restaurant_notified_at < pickup_at', - 'restaurant_confirmed_at < restaurant_ready_at', - 'restaurant_confirmed_at < pickup_at', - 'restaurant_ready_at < pickup_at', - 'dispatch_at < first_estimated_delivery_at', - 'dispatch_at < courier_notified_at', - 'dispatch_at < courier_accepted_at', - 'dispatch_at < reached_pickup_at', - 'dispatch_at < pickup_at', - 'dispatch_at < left_pickup_at', - 'dispatch_at < reached_delivery_at', - 'dispatch_at < delivery_at', - 'courier_notified_at < courier_accepted_at', - 'courier_notified_at < reached_pickup_at', - 'courier_notified_at < pickup_at', - 'courier_notified_at < left_pickup_at', - 'courier_notified_at < reached_delivery_at', - 'courier_notified_at < delivery_at', - 'courier_accepted_at < reached_pickup_at', - 'courier_accepted_at < pickup_at', - 'courier_accepted_at < left_pickup_at', - 'courier_accepted_at < reached_delivery_at', - 'courier_accepted_at < delivery_at', - 'reached_pickup_at < pickup_at', - 'reached_pickup_at < left_pickup_at', - 'reached_pickup_at < reached_delivery_at', - 'reached_pickup_at < delivery_at', - 'pickup_at < left_pickup_at', - 'pickup_at < reached_delivery_at', - 'pickup_at < delivery_at', - 'left_pickup_at < reached_delivery_at', - 'left_pickup_at < delivery_at', - 'reached_delivery_at < delivery_at', + "placed_at < scheduled_delivery_at", + "placed_at < cancelled_at", + "placed_at < restaurant_notified_at", + "placed_at < restaurant_confirmed_at", + "placed_at < restaurant_ready_at", + "placed_at < dispatch_at", + "placed_at < first_estimated_delivery_at", + "placed_at < courier_notified_at", + "placed_at < courier_accepted_at", + "placed_at < reached_pickup_at", + "placed_at < pickup_at", + "placed_at < left_pickup_at", + "placed_at < reached_delivery_at", + "placed_at < delivery_at", + "cancelled_at > restaurant_notified_at", + "cancelled_at > restaurant_confirmed_at", + "cancelled_at > restaurant_ready_at", + "cancelled_at > dispatch_at", + "cancelled_at > courier_notified_at", + "cancelled_at > courier_accepted_at", + "cancelled_at > reached_pickup_at", + "restaurant_notified_at < restaurant_confirmed_at", + "restaurant_notified_at < restaurant_ready_at", + "restaurant_notified_at < pickup_at", + "restaurant_confirmed_at < restaurant_ready_at", + "restaurant_confirmed_at < pickup_at", + "restaurant_ready_at < pickup_at", + "dispatch_at < first_estimated_delivery_at", + "dispatch_at < courier_notified_at", + "dispatch_at < courier_accepted_at", + "dispatch_at < reached_pickup_at", + "dispatch_at < pickup_at", + "dispatch_at < left_pickup_at", + "dispatch_at < reached_delivery_at", + "dispatch_at < delivery_at", + "courier_notified_at < courier_accepted_at", + "courier_notified_at < reached_pickup_at", + "courier_notified_at < pickup_at", + "courier_notified_at < left_pickup_at", + "courier_notified_at < reached_delivery_at", + "courier_notified_at < delivery_at", + "courier_accepted_at < reached_pickup_at", + "courier_accepted_at < pickup_at", + "courier_accepted_at < left_pickup_at", + "courier_accepted_at < reached_delivery_at", + "courier_accepted_at < delivery_at", + "reached_pickup_at < pickup_at", + "reached_pickup_at < left_pickup_at", + "reached_pickup_at < reached_delivery_at", + "reached_pickup_at < delivery_at", + "pickup_at < left_pickup_at", + "pickup_at < reached_delivery_at", + "pickup_at < delivery_at", + "left_pickup_at < reached_delivery_at", + "left_pickup_at < delivery_at", + "reached_delivery_at < delivery_at", ), ) ), @@ -366,23 +366,23 @@ def upgrade(): ) op.create_index( - op.f('ix_replay_simulations_on_city_id'), - 'replay_simulations', - ['city_id'], + op.f("ix_replay_simulations_on_city_id"), + "replay_simulations", + ["city_id"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_replay_simulations_on_strategy'), - 'replay_simulations', - ['strategy'], + op.f("ix_replay_simulations_on_strategy"), + "replay_simulations", + ["strategy"], unique=False, schema=config.CLEAN_SCHEMA, ) op.create_index( - op.f('ix_replayed_orders_on_courier_id'), - 'replayed_orders', - ['courier_id'], + op.f("ix_replayed_orders_on_courier_id"), + "replayed_orders", + ["courier_id"], unique=False, schema=config.CLEAN_SCHEMA, ) @@ -390,11 +390,11 @@ def upgrade(): def downgrade(): """Downgrade to revision b4dd0b8903a5.""" - op.drop_table('replayed_orders', schema=config.CLEAN_SCHEMA) - op.drop_table('replay_simulations', schema=config.CLEAN_SCHEMA) + op.drop_table("replayed_orders", schema=config.CLEAN_SCHEMA) + op.drop_table("replay_simulations", schema=config.CLEAN_SCHEMA) op.drop_constraint( - 'uq_orders_on_id_ad_hoc', - 'orders', + "uq_orders_on_id_ad_hoc", + "orders", type_=None, schema=config.CLEAN_SCHEMA, ) diff --git a/noxfile.py b/noxfile.py index 6756716..8c55b02 100644 --- a/noxfile.py +++ b/noxfile.py @@ -64,35 +64,35 @@ def load_pyproject_toml() -> collections.defaultdict[str, Any]: so, missing keys and tables (i.e., "sections" in the .ini format) do not result in `KeyError`s but return empty `nested_defaultdict`s. """ - return defaultify(nox.project.load_toml('pyproject.toml')) + return defaultify(nox.project.load_toml("pyproject.toml")) def load_supported_python_versions(*, reverse: bool = False) -> list[str]: """Parse the Python versions from the pyproject.toml file.""" pyproject = load_pyproject_toml() version_names = { - classifier.rsplit(' ')[-1] - for classifier in pyproject['project']['classifiers'] - if classifier.startswith('Programming Language :: Python :: ') + classifier.rsplit(" ")[-1] + for classifier in pyproject["project"]["classifiers"] + if classifier.startswith("Programming Language :: Python :: ") } return sorted(version_names, key=pkg_version.Version, reverse=reverse) -PACKAGE = 'velofy' -PACKAGE_LOCATION = 'src/' +PACKAGE = "velofy" +PACKAGE_LOCATION = "src/" -DOCS_BUILD = '.cache/docs/' -DOCS_LOCATION = 'docs/' +DOCS_BUILD = ".cache/docs/" +DOCS_LOCATION = "docs/" -TESTS_LOCATION = 'tests/' +TESTS_LOCATION = "tests/" # Locations of all *.py files SRC_LOCATIONS = ( - f'{DOCS_LOCATION}conf.py', - 'migrations/env.py', - 'migrations/versions/', - 'noxfile.py', - 'scripts/', + f"{DOCS_LOCATION}conf.py", + "migrations/env.py", + "migrations/versions/", + "noxfile.py", + "scripts/", PACKAGE_LOCATION, TESTS_LOCATION, ) @@ -102,13 +102,13 @@ SUPPORTED_PYTHONS = load_supported_python_versions() # Must be listed in the "classifiers", which is checked at the bottom # of this file, and satisfy "requires-python" in pyproject.toml -MAIN_PYTHON = '3.13' +MAIN_PYTHON = "3.13" -nox.options.default_venv_backend = 'uv' +nox.options.default_venv_backend = "uv" # Use a unified .cache/ folder for all tools -nox.options.envdir = '.cache/nox' +nox.options.envdir = ".cache/nox" # All tools except `git` and `uv` are project dependencies # => Avoid accidental successes if the environment is not set up properly @@ -116,30 +116,30 @@ nox.options.error_on_external_run = True # Always start with fresh virtual environments # unless the "-r" or "-R" flags are passed in -nox.options.reuse_venv = 'no' +nox.options.reuse_venv = "no" # Do not run further sessions once one fails nox.options.stop_on_first_error = True # Run only the code quality checks by default nox.options.sessions = ( - 'format', - 'lint', - 'test', - 'doctest', + "format", + "lint", + "test", + "doctest", ) # Make `uv` use its own `python` # because only then are the headers needed to build `rpy2` from source included -os.environ.setdefault('UV_PYTHON_PREFERENCE', 'only-managed') +os.environ.setdefault("UV_PYTHON_PREFERENCE", "only-managed") # Where to keep temporary files (e.g., the constraints file in `install_pinned()`) -tempfile.tempdir = '.cache/tmp' +tempfile.tempdir = ".cache/tmp" os.makedirs(tempfile.tempdir, exist_ok=True) -@nox.session(name='format', python=MAIN_PYTHON) +@nox.session(name="format", python=MAIN_PYTHON) def format_code(session: Session) -> None: """Format source files with `autoflake`, `black`, and `isort`. @@ -150,24 +150,24 @@ def format_code(session: Session) -> None: # The formatters do not need `velofy` installed # because they work on the source files directly - install_pinned(session, 'autoflake', 'black', 'isort') + install_pinned(session, "autoflake", "black", "isort") # Interpret extra arguments as `locations` of source files locations = session.posargs or SRC_LOCATIONS # `autoflake` changes files only with the "in-place = true" # in the "[tool.autoflake]" section in pyproject.toml - session.run('autoflake', '--version') - session.run('autoflake', *locations) + session.run("autoflake", "--version") + session.run("autoflake", *locations) - session.run('black', '--version') - session.run('black', *locations) + session.run("black", "--version") + session.run("black", *locations) - session.run('isort', '--version') - session.run('isort', *locations) + session.run("isort", "--version") + session.run("isort", *locations) -@nox.session(name='lint', python=MAIN_PYTHON) +@nox.session(name="lint", python=MAIN_PYTHON) def lint_code(session: Session) -> None: """Lint source files with `flake8` and `isort`. @@ -180,19 +180,19 @@ def lint_code(session: Session) -> None: # because they work on the source files directly install_pinned( session, - 'flake8', - 'flake8-annotations', - 'flake8-bandit', - 'flake8-black', - 'flake8-broken-line', - 'flake8-bugbear', - 'flake8-commas', - 'flake8-comprehensions', - 'flake8-debugger', - 'flake8-docstrings', - 'flake8-pyproject', - 'flake8-pytest-style', - 'isort', + "flake8", + "flake8-annotations", + "flake8-bandit", + "flake8-black", + "flake8-broken-line", + "flake8-bugbear", + "flake8-commas", + "flake8-comprehensions", + "flake8-debugger", + "flake8-docstrings", + "flake8-pyproject", + "flake8-pytest-style", + "isort", # TODO: See comment on `mypy` below # 'mypy', ) @@ -202,11 +202,11 @@ def lint_code(session: Session) -> None: # `flake8` reads the "[tool.flake8]" section in pyproject.toml # only with the `flake8-pyproject` plugin installed - session.run('flake8', '--version') - session.run('flake8', *locations) + session.run("flake8", "--version") + session.run("flake8", *locations) - session.run('isort', '--version') - session.run('isort', '--check-only', *locations) + session.run("isort", "--version") + session.run("isort", "--check-only", *locations) # TODO: Include `mypy` once it passes # - Only for the *.py files to be packaged @@ -216,7 +216,7 @@ def lint_code(session: Session) -> None: # session.run('mypy', PACKAGE_LOCATION) -@nox.session(name='test', python=MAIN_PYTHON) +@nox.session(name="test", python=MAIN_PYTHON) def test_code(session: Session) -> None: """Run the unit and integration tests with `pytest`. @@ -229,32 +229,32 @@ def test_code(session: Session) -> None: install_pinned( session, # The tests import `velofy`, so it and its dependencies must be installed - '.', # => A non-editable copy as it would really be installed - 'factory-boy', - 'Faker', - 'packaging', - 'pytest', - 'pytest-cov', - 'pytest-env', - 'pytest-mock', + ".", # => A non-editable copy as it would really be installed + "factory-boy", + "Faker", + "packaging", + "pytest", + "pytest-cov", + "pytest-env", + "pytest-mock", ) - session.run('pytest', '--version') + session.run("pytest", "--version") pytest_default_args = ( # See "[tool.coverage]" in pyproject.toml for `coverage` settings, # for example, branch coverage and report format, # and "[tool.coverage.paths]" mapping `coverage` to src/ - '--cov', - '--no-cov-on-fail', - '--cov-fail-under=100', + "--cov", + "--no-cov-on-fail", + "--cov-fail-under=100", TESTS_LOCATION, ) - session.run('pytest', *(session.posargs or pytest_default_args)) + session.run("pytest", *(session.posargs or pytest_default_args)) -@nox.session(name='doctest', python=MAIN_PYTHON) +@nox.session(name="doctest", python=MAIN_PYTHON) def test_docstrings(session: Session) -> None: """Test the code snippets in the docstrings with `xdoctest`. @@ -264,22 +264,22 @@ def test_docstrings(session: Session) -> None: """ start(session) - install_pinned(session, '.', 'xdoctest[colors]') + install_pinned(session, ".", "xdoctest[colors]") # As `pytest-env` does for `pytest`, # keep `velofy` from connecting to the production database - session.env['TESTING'] = 'true' + session.env["TESTING"] = "true" session.run( - 'python', - '-m', - 'xdoctest', + "python", + "-m", + "xdoctest", PACKAGE, - *(session.posargs or ('all',)), + *(session.posargs or ("all",)), ) -@nox.session(name='docs', python=MAIN_PYTHON) +@nox.session(name="docs", python=MAIN_PYTHON) def build_docs(session: Session) -> None: """Build the documentation with `sphinx`. @@ -289,21 +289,21 @@ def build_docs(session: Session) -> None: # The `sphinx-autodoc` extension imports `velofy` to read the docstrings # => `velofy` and its dependencies must be installed - install_pinned(session, '.', 'sphinx', 'sphinx-autodoc-typehints') + install_pinned(session, ".", "sphinx", "sphinx-autodoc-typehints") # As `pytest-env` does for `pytest`, # keep `velofy` from connecting to the production database - session.env['TESTING'] = 'true' + session.env["TESTING"] = "true" - session.run('sphinx-build', DOCS_LOCATION, DOCS_BUILD) + session.run("sphinx-build", DOCS_LOCATION, DOCS_BUILD) # Verify that all external links return 200 OK - session.run('sphinx-build', '-b', 'linkcheck', DOCS_LOCATION, DOCS_BUILD) + session.run("sphinx-build", "-b", "linkcheck", DOCS_LOCATION, DOCS_BUILD) - print(f'Docs are available at {os.getcwd()}/{DOCS_BUILD}index.html') + print(f"Docs are available at {os.getcwd()}/{DOCS_BUILD}index.html") -@nox.session(name='venv', python=MAIN_PYTHON, venv_backend='none') +@nox.session(name="venv", python=MAIN_PYTHON, venv_backend="none") def create_develop_environment(session: Session) -> None: """Set up the local develop environment in ".venv". @@ -316,24 +316,24 @@ def create_develop_environment(session: Session) -> None: Then, `uv run` only uses that environment with "UV_PROJECT_ENVIRONMENT" set to the same location. """ - location, *further_args = session.posargs or ('.venv',) + location, *further_args = session.posargs or (".venv",) if further_args: - session.error('Must provide exactly one location') + session.error("Must provide exactly one location") # All dependency groups are installed because of "default-groups = 'all'" # in the "[tool.uv]" section in pyproject.toml session.run( - 'uv', - 'sync', - '--all-extras', - '--locked', - env={'UV_PROJECT_ENVIRONMENT': location}, + "uv", + "sync", + "--all-extras", + "--locked", + env={"UV_PROJECT_ENVIRONMENT": location}, external=True, ) -@nox.session(name='deps-audit', python=MAIN_PYTHON, reuse_venv=False) +@nox.session(name="deps-audit", python=MAIN_PYTHON, reuse_venv=False) def audit_pinned_dependencies(session: Session) -> None: """Check dependencies for vulnerabilities with `pip-audit`. @@ -348,36 +348,36 @@ def audit_pinned_dependencies(session: Session) -> None: start(session) # `pip-audit` is not pinned to always check with its latest version - session.install('pip-audit') + session.install("pip-audit") - with tempfile.NamedTemporaryFile(suffix='.txt') as requirements_txt: + with tempfile.NamedTemporaryFile(suffix=".txt") as requirements_txt: session.run( - 'uv', - 'export', - '--all-extras', - '--all-groups', - '--locked', - '--no-emit-project', - '--quiet', - f'--output-file={requirements_txt.name}', + "uv", + "export", + "--all-extras", + "--all-groups", + "--locked", + "--no-emit-project", + "--quiet", + f"--output-file={requirements_txt.name}", ) - session.run('pip-audit', '--version') + session.run("pip-audit", "--version") session.run( - 'pip-audit', - '--cache-dir=.cache/pip-audit', - '--disable-pip', - '--progress-spinner=off', - f'--requirement={requirements_txt.name}', - '--strict', + "pip-audit", + "--cache-dir=.cache/pip-audit", + "--disable-pip", + "--progress-spinner=off", + f"--requirement={requirements_txt.name}", + "--strict", # TODO: Remove these ignores once we upgrade to `black` v26 - '--ignore-vuln=PYSEC-2026-2120', - '--ignore-vuln=PYSEC-2026-2121', - '--ignore-vuln=CVE-2026-114134', + "--ignore-vuln=PYSEC-2026-2120", + "--ignore-vuln=PYSEC-2026-2121", + "--ignore-vuln=CVE-2026-114134", ) -@nox.session(name='deps-lock', python=MAIN_PYTHON, venv_backend='none') +@nox.session(name="deps-lock", python=MAIN_PYTHON, venv_backend="none") def lock_dependencies(session: Session) -> None: """Lock dependencies in pyproject.toml into uv.lock. @@ -392,12 +392,12 @@ def lock_dependencies(session: Session) -> None: # and call `upgrade_dependencies()` directly # because `session.notify()` starts sessions with a new # `nox.Session` object that does not have the flag set - session.env['_lock_only'] = 'true' + session.env["_lock_only"] = "true" upgrade_dependencies(session) -@nox.session(name='deps-upgrade', python=MAIN_PYTHON, venv_backend='none') +@nox.session(name="deps-upgrade", python=MAIN_PYTHON, venv_backend="none") def upgrade_dependencies(session: Session) -> None: """Pin dependencies in uv.lock to their latest MINOR/PATCH versions. @@ -417,20 +417,20 @@ def upgrade_dependencies(session: Session) -> None: So, the obtained upgrades must still be manually `git commit`ed into the repository. """ - if session.env.get('_lock_only'): + if session.env.get("_lock_only"): upgrade = [] elif session.posargs: - upgrade = [f'--upgrade-package={pkg_name}' for pkg_name in session.posargs] + upgrade = [f"--upgrade-package={pkg_name}" for pkg_name in session.posargs] else: - upgrade = ['--upgrade'] + upgrade = ["--upgrade"] - session.run('uv', '--version', external=True) - session.run('uv', 'lock', *upgrade, external=True) + session.run("uv", "--version", external=True) + session.run("uv", "lock", *upgrade, external=True) - session.run('git', 'diff', '--stat', 'uv.lock', external=True) + session.run("git", "diff", "--stat", "uv.lock", external=True) -@nox.session(name='deps-upgrade-check', python=MAIN_PYTHON) +@nox.session(name="deps-upgrade-check", python=MAIN_PYTHON) def check_dependency_upgrades(session: Session) -> None: """Check the dependencies in uv.lock for upgrades. @@ -445,17 +445,17 @@ def check_dependency_upgrades(session: Session) -> None: start(session) # The script only uses the standard library => Nothing to install - session.run('python', 'scripts/get_update_info_for_dependencies.py') + session.run("python", "scripts/get_update_info_for_dependencies.py") -@nox.session(name='init-project', python=MAIN_PYTHON, venv_backend='none') +@nox.session(name="init-project", python=MAIN_PYTHON, venv_backend="none") def initialize_project(session: Session) -> None: """Install the `pre-commit` hooks.""" # .pre-commit-config.yaml sets the hook types via "default_install_hook_types" - session.run('uv', 'run', 'pre-commit', 'install') + session.run("uv", "run", "pre-commit", "install") -@nox.session(name='clean-cwd', python=MAIN_PYTHON, venv_backend='none') +@nox.session(name="clean-cwd", python=MAIN_PYTHON, venv_backend="none") def clean_cwd(session: Session) -> None: """Remove (almost) all glob patterns listed in git's ignore file. @@ -468,19 +468,19 @@ def clean_cwd(session: Session) -> None: do_not_accept_arguments(session) do_not_remove = { - '.env', - '.envrc', - '.python-version', - '.venv', + ".env", + ".envrc", + ".python-version", + ".venv", } - with pathlib.Path('.gitignore').open() as fp: + with pathlib.Path(".gitignore").open() as fp: ignored_patterns = { - pattern for pattern in fp if pattern and not pattern.startswith(('#', '!')) + pattern for pattern in fp if pattern and not pattern.startswith(("#", "!")) } - with pathlib.Path('.gitignore').open() as fp: - excluded_patterns = {pattern[1:] for pattern in fp if pattern.startswith('!')} + with pathlib.Path(".gitignore").open() as fp: + excluded_patterns = {pattern[1:] for pattern in fp if pattern.startswith("!")} # Paths are resolved into absolute ones to avoid accidental matches excluded_paths = { @@ -488,12 +488,12 @@ def clean_cwd(session: Session) -> None: for path in do_not_remove | set(_expand(*excluded_patterns)) } - for path in itertools.chain([pathlib.Path('.cache')], _expand(*ignored_patterns)): + for path in itertools.chain([pathlib.Path(".cache")], _expand(*ignored_patterns)): # The `path` must not be a sub-path of an `excluded_path` if {path, *path.parents} & excluded_paths: continue - session.run('rm', '-rf', path) + session.run("rm", "-rf", path) def _expand(*patterns: str) -> Generator[pathlib.Path, None, None]: @@ -521,9 +521,9 @@ def do_not_accept_arguments(session: Session, *, raise_error: bool = True) -> No msg = 'be run without any positional arguments behind the "--"' if raise_error: - session.error(f'Must {msg}') + session.error(f"Must {msg}") else: - session.warn(f'Should {msg}') + session.warn(f"Should {msg}") def do_not_reuse(session: Session, *, raise_error: bool = True) -> None: @@ -532,38 +532,38 @@ def do_not_reuse(session: Session, *, raise_error: bool = True) -> None: msg = 'be run without the "-r" and "-R" flags' if raise_error: - session.error(f'Must {msg}') + session.error(f"Must {msg}") else: - session.warn(f'Should {msg}') + session.warn(f"Should {msg}") def start(session: Session) -> None: """Show generic info about a session.""" if session.posargs: - session.debug(f'Received extra arguments: {session.posargs}') + session.debug(f"Received extra arguments: {session.posargs}") - session.debug('Some generic information about the environment') + session.debug("Some generic information about the environment") - session.run('python', '--version') - session.run('python', '-c', 'import sys; print(sys.executable)') - session.run('python', '-c', 'import sys; print(sys.path)') - session.run('python', '-c', 'import os; print(os.getcwd())') - session.run('python', '-c', 'import os; print(os.environ["PATH"])') + session.run("python", "--version") + session.run("python", "-c", "import sys; print(sys.executable)") + session.run("python", "-c", "import sys; print(sys.path)") + session.run("python", "-c", "import os; print(os.getcwd())") + session.run("python", "-c", 'import os; print(os.environ["PATH"])') - session.env['BLACK_CACHE_DIR'] = '.cache/black' + session.env["BLACK_CACHE_DIR"] = ".cache/black" session.run( - 'mkdir', - '-p', + "mkdir", + "-p", *( - f'.cache/{dir_}' + f".cache/{dir_}" for dir_ in ( - 'black', - 'coverage', - 'mypy', - 'nox', - 'pytest', - 'tmp', + "black", + "coverage", + "mypy", + "nox", + "pytest", + "tmp", ) ), external=True, @@ -590,20 +590,20 @@ def install_pinned( if skip_install(session): return - with tempfile.NamedTemporaryFile(suffix='.txt') as constraints_txt: + with tempfile.NamedTemporaryFile(suffix=".txt") as constraints_txt: session.run( - 'uv', - 'export', - '--all-extras', - '--all-groups', - '--locked', - '--no-emit-project', - '--no-hashes', - '--quiet', - f'--output-file={constraints_txt.name}', + "uv", + "export", + "--all-extras", + "--all-groups", + "--locked", + "--no-emit-project", + "--no-hashes", + "--quiet", + f"--output-file={constraints_txt.name}", ) session.install( - f'--constraint={constraints_txt.name}', + f"--constraint={constraints_txt.name}", *packages_or_pip_args, **kwargs, ) @@ -623,5 +623,5 @@ def skip_install(session: Session) -> bool: if MAIN_PYTHON not in SUPPORTED_PYTHONS: - msg = f'MAIN_PYTHON version, v{MAIN_PYTHON}, is not in SUPPORTED_PYTHONS' + msg = f"MAIN_PYTHON version, v{MAIN_PYTHON}, is not in SUPPORTED_PYTHONS" raise RuntimeError(msg) diff --git a/pyproject.toml b/pyproject.toml index e3e4458..bbb6ecf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -141,8 +141,6 @@ target-version = ["py313"] line-length = 88 -skip-string-normalization = true # `wemake-python-styleguide` enforces single quotes - [tool.coverage] diff --git a/src/velofy/__init__.py b/src/velofy/__init__.py index 2147079..4c513c6 100644 --- a/src/velofy/__init__.py +++ b/src/velofy/__init__.py @@ -19,11 +19,11 @@ try: _pkg_info = _metadata.metadata(__name__) except _metadata.PackageNotFoundError: # pragma: no cover - __author__ = 'unknown' - __pkg_name__ = 'unknown' - __version__ = 'unknown' + __author__ = "unknown" + __pkg_name__ = "unknown" + __version__ = "unknown" else: - __author__ = _pkg_info['author'] - __pkg_name__ = _pkg_info['name'] - __version__ = _pkg_info['version'] + __author__ = _pkg_info["author"] + __pkg_name__ = _pkg_info["name"] + __version__ = _pkg_info["version"] diff --git a/src/velofy/configuration.py b/src/velofy/configuration.py index 6d2d5dc..a50fc0a 100644 --- a/src/velofy/configuration.py +++ b/src/velofy/configuration.py @@ -16,8 +16,8 @@ import warnings def random_schema_name() -> str: """Generate a random PostgreSQL schema name for testing.""" - return 'temp_{name}'.format( - name=''.join( + return "temp_{name}".format( + name="".join( (random.choice(string.ascii_lowercase) for _ in range(10)), # noqa:S311 ), ) @@ -54,33 +54,33 @@ class Config: TRAIN_HORIZONS = [7, 8] # The demand forecasting methods used in the simulations. - FORECASTING_METHODS = ['hets', 'rtarima'] + FORECASTING_METHODS = ["hets", "rtarima"] # Colors for the visualizations ins `folium`. - RESTAURANT_COLOR = 'red' - CUSTOMER_COLOR = 'blue' - NEUTRAL_COLOR = 'black' + RESTAURANT_COLOR = "red" + CUSTOMER_COLOR = "blue" + NEUTRAL_COLOR = "black" # Implementation-specific settings # -------------------------------- - DATABASE_URI = os.getenv('DATABASE_URI') - GOOGLE_MAPS_API_KEY = os.getenv('GOOGLE_MAPS_API_KEY') + DATABASE_URI = os.getenv("DATABASE_URI") + GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY") # The PostgreSQL schema that holds the tables with the original data. - ORIGINAL_SCHEMA = os.getenv('ORIGINAL_SCHEMA') or 'public' + ORIGINAL_SCHEMA = os.getenv("ORIGINAL_SCHEMA") or "public" # The PostgreSQL schema that holds the tables with the cleaned data. - CLEAN_SCHEMA = os.getenv('CLEAN_SCHEMA') or 'clean' + CLEAN_SCHEMA = os.getenv("CLEAN_SCHEMA") or "clean" - ALEMBIC_TABLE = 'alembic_version' - ALEMBIC_TABLE_SCHEMA = 'public' + ALEMBIC_TABLE = "alembic_version" + ALEMBIC_TABLE_SCHEMA = "public" - R_LIBS_PATH = os.getenv('R_LIBS') + R_LIBS_PATH = os.getenv("R_LIBS") def __repr__(self) -> str: """Non-literal text representation.""" - return '' + return "" class ProductionConfig(Config): @@ -94,11 +94,11 @@ class TestingConfig(Config): TESTING = True - DATABASE_URI = os.getenv('DATABASE_URI_TESTING') or Config.DATABASE_URI - CLEAN_SCHEMA = os.getenv('CLEAN_SCHEMA_TESTING') or random_schema_name() + DATABASE_URI = os.getenv("DATABASE_URI_TESTING") or Config.DATABASE_URI + CLEAN_SCHEMA = os.getenv("CLEAN_SCHEMA_TESTING") or random_schema_name() -def make_config(env: str = 'production') -> Config: +def make_config(env: str = "production") -> Config: """Create a new `Config` object. Args: @@ -112,9 +112,9 @@ def make_config(env: str = 'production') -> Config: """ # noqa:DAR203 config: Config # otherwise mypy is confused - if env.strip().lower() == 'production': + if env.strip().lower() == "production": config = ProductionConfig() - elif env.strip().lower() == 'testing': + elif env.strip().lower() == "testing": config = TestingConfig() else: raise ValueError("Must be either 'production' or 'testing'") @@ -123,22 +123,22 @@ def make_config(env: str = 'production') -> Config: # As pytest sets the "TESTING" environment variable explicitly, # the warning is only emitted if the code is not run by pytest. # We see the bad configuration immediately as all "db" tests fail. - if config.DATABASE_URI is None and not os.getenv('TESTING'): + if config.DATABASE_URI is None and not os.getenv("TESTING"): warnings.warn( - 'Bad configuration: no DATABASE_URI set in the environment', + "Bad configuration: no DATABASE_URI set in the environment", stacklevel=2, ) # Some functionalities require R and some packages installed. # To ensure isolation and reproducibility, the projects keeps the R dependencies # in a project-local folder that must be set in the environment. - if config.R_LIBS_PATH is None and not os.getenv('TESTING'): + if config.R_LIBS_PATH is None and not os.getenv("TESTING"): warnings.warn( - 'Bad configuration: no R_LIBS set in the environment', + "Bad configuration: no R_LIBS set in the environment", stacklevel=2, ) return config -config = make_config('testing' if os.getenv('TESTING') else 'production') +config = make_config("testing" if os.getenv("TESTING") else "production") diff --git a/src/velofy/console/__init__.py b/src/velofy/console/__init__.py index 3aaa69b..600391d 100644 --- a/src/velofy/console/__init__.py +++ b/src/velofy/console/__init__.py @@ -7,5 +7,5 @@ from velofy.console import main cli = main.entry_point -cli.add_command(forecasts.tactical_heuristic, name='tactical-forecasts') +cli.add_command(forecasts.tactical_heuristic, name="tactical-forecasts") cli.add_command(gridify.gridify) diff --git a/src/velofy/console/decorators.py b/src/velofy/console/decorators.py index 2a021cb..7c6fd6d 100644 --- a/src/velofy/console/decorators.py +++ b/src/velofy/console/decorators.py @@ -18,17 +18,17 @@ def db_revision( @functools.wraps(func) def ensure(*args: Any, **kwargs: Any) -> Any: """Do not execute the `func` if the revision does not match.""" - if not os.getenv('TESTING'): + if not os.getenv("TESTING"): result = subprocess.run( # noqa:S603,S607 - ['alembic', 'current'], + ["alembic", "current"], capture_output=True, check=False, - encoding='utf8', + encoding="utf8", ) if not result.stdout.startswith(rev): click.echo( - click.style(f'Database is not at revision {rev}', fg='red'), + click.style(f"Database is not at revision {rev}", fg="red"), ) sys.exit(1) diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index 316ea48..b521623 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -19,11 +19,11 @@ from velofy.forecasts import timify @click.command() -@click.argument('city', default='Paris', type=str) -@click.argument('side_length', default=1000, type=int) -@click.argument('time_step', default=60, type=int) -@click.argument('train_horizon', default=8, type=int) -@decorators.db_revision('8bfb928a31f8') +@click.argument("city", default="Paris", type=str) +@click.argument("side_length", default=1000, type=int) +@click.argument("time_step", default=60, type=int) +@click.argument("train_horizon", default=8, type=int) +@decorators.db_revision("8bfb928a31f8") def tactical_heuristic( # noqa:C901 city: str, side_length: int, @@ -77,21 +77,21 @@ def tactical_heuristic( # noqa:C901 if grid.side_length == side_length: break else: - click.echo(f'SIDE_LENGTH must be in {config.GRID_SIDE_LENGTHS}') + click.echo(f"SIDE_LENGTH must be in {config.GRID_SIDE_LENGTHS}") sys.exit(1) if time_step not in config.TIME_STEPS: - click.echo(f'TIME_STEP must be in {config.TIME_STEPS}') + click.echo(f"TIME_STEP must be in {config.TIME_STEPS}") sys.exit(1) if train_horizon not in config.TRAIN_HORIZONS: - click.echo(f'TRAIN_HORIZON must be in {config.TRAIN_HORIZONS}') + click.echo(f"TRAIN_HORIZON must be in {config.TRAIN_HORIZONS}") sys.exit(1) click.echo( - 'Parameters: ' - + f'city={city}, grid.side_length={side_length}, ' - + f'time_step={time_step}, train_horizon={train_horizon}', + "Parameters: " + + f"city={city}, grid.side_length={side_length}, " + + f"time_step={time_step}, train_horizon={train_horizon}", ) # Load the historic order data. @@ -131,8 +131,8 @@ def tactical_heuristic( # noqa:C901 train_horizon=train_horizon, ) click.echo( - f'Predicting pixel #{pixel.id} in {city} ' - + f'for {predict_day} with {model.name}', + f"Predicting pixel #{pixel.id} in {city} " + + f"for {predict_day} with {model.name}", ) # Only loop over the time steps corresponding to working hours. diff --git a/src/velofy/console/gridify.py b/src/velofy/console/gridify.py index da2d17c..5107fd4 100644 --- a/src/velofy/console/gridify.py +++ b/src/velofy/console/gridify.py @@ -8,7 +8,7 @@ from velofy.console import decorators @click.command() -@decorators.db_revision('e86290e7305e') +@decorators.db_revision("e86290e7305e") def gridify() -> None: # pragma: no cover note:b1f68d24 """Create grids for all cities. @@ -21,18 +21,18 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 All data are persisted to the database. """ cities = db.session.query(db.City).all() - click.echo(f'{len(cities)} cities retrieved from the database') + click.echo(f"{len(cities)} cities retrieved from the database") for city in cities: - click.echo(f'\nCreating grids for {city.name}') + click.echo(f"\nCreating grids for {city.name}") for side_length in config.GRID_SIDE_LENGTHS: - click.echo(f'Creating grid with a side length of {side_length} meters') + click.echo(f"Creating grid with a side length of {side_length} meters") grid = db.Grid.gridify(city=city, side_length=side_length) db.session.add(grid) - click.echo(f' -> created {len(grid.pixels)} pixels') + click.echo(f" -> created {len(grid.pixels)} pixels") # Because the number of assigned addresses is the same across # different `side_length`s, we can take any `grid` from the `city`. @@ -43,7 +43,7 @@ def gridify() -> None: # pragma: no cover note:b1f68d24 .count() ) click.echo( - f'=> assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}', # noqa:E501 + f"=> assigned {n_assigned} out of {len(city.addresses)} addresses in {city.name}", # noqa:E501 ) db.session.commit() diff --git a/src/velofy/console/main.py b/src/velofy/console/main.py index a9333d7..0874530 100644 --- a/src/velofy/console/main.py +++ b/src/velofy/console/main.py @@ -16,18 +16,18 @@ def show_version(ctx: cli_core.Context, _param: Any, value: bool) -> None: return # Mimic the colors of `poetry version`. - pkg_name = click.style(velofy.__pkg_name__, fg='green') - version = click.style(velofy.__version__, fg='blue') + pkg_name = click.style(velofy.__pkg_name__, fg="green") + version = click.style(velofy.__version__, fg="blue") # Include a warning for development versions. - warning = click.style(' (development)', fg='red') if '.dev' in version else '' - click.echo(f'{pkg_name}, version {version}{warning}') + warning = click.style(" (development)", fg="red") if ".dev" in version else "" + click.echo(f"{pkg_name}, version {version}{warning}") ctx.exit() @click.group() @click.option( - '--version', - '-V', + "--version", + "-V", is_flag=True, callback=show_version, is_eager=True, diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 9c237c4..5c1440a 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -19,7 +19,7 @@ from velofy.db import utils class Address(meta.Base): """An address of a `Customer` or a `Restaurant` on the UDP.""" - __tablename__ = 'addresses' + __tablename__ = "addresses" # Columns id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) @@ -29,7 +29,7 @@ class Address(meta.Base): latitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) longitude = sa.Column(postgresql.DOUBLE_PRECISION, nullable=False) city_id = sa.Column(sa.SmallInteger, nullable=False, index=True) - city_name = sa.Column('city', sa.Unicode(length=25), nullable=False) + city_name = sa.Column("city", sa.Unicode(length=25), nullable=False) zip_code = sa.Column(sa.Integer, nullable=False, index=True) street = sa.Column(sa.Unicode(length=80), nullable=False) floor = sa.Column(sa.SmallInteger) @@ -37,52 +37,52 @@ class Address(meta.Base): # Constraints __table_args__ = ( sa.ForeignKeyConstraint( - ['primary_id'], - ['addresses.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["primary_id"], + ["addresses.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['city_id'], - ['cities.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["city_id"], + ["cities.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.CheckConstraint( - '-90 <= latitude AND latitude <= 90', - name='latitude_between_90_degrees', + "-90 <= latitude AND latitude <= 90", + name="latitude_between_90_degrees", ), sa.CheckConstraint( - '-180 <= longitude AND longitude <= 180', - name='longitude_between_180_degrees', + "-180 <= longitude AND longitude <= 180", + name="longitude_between_180_degrees", ), # Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`. - sa.UniqueConstraint('id', 'city_id'), + sa.UniqueConstraint("id", "city_id"), sa.CheckConstraint( - '30000 <= zip_code AND zip_code <= 99999', - name='valid_zip_code', + "30000 <= zip_code AND zip_code <= 99999", + name="valid_zip_code", ), - sa.CheckConstraint('0 <= floor AND floor <= 40', name='realistic_floor'), + sa.CheckConstraint("0 <= floor AND floor <= 40", name="realistic_floor"), ) # Relationships - city = orm.relationship('City', back_populates='addresses') - restaurants = orm.relationship('Restaurant', back_populates='address') + city = orm.relationship("City", back_populates="addresses") + restaurants = orm.relationship("Restaurant", back_populates="address") orders_picked_up = orm.relationship( - 'Order', - back_populates='pickup_address', - foreign_keys='[Order.pickup_address_id]', + "Order", + back_populates="pickup_address", + foreign_keys="[Order.pickup_address_id]", ) orders_delivered = orm.relationship( - 'Order', - back_populates='delivery_address', - foreign_keys='[Order.delivery_address_id]', + "Order", + back_populates="delivery_address", + foreign_keys="[Order.delivery_address_id]", ) - pixels = orm.relationship('AddressPixelAssociation', back_populates='address') + pixels = orm.relationship("AddressPixelAssociation", back_populates="address") def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}({street} in {city})>'.format( + return "<{cls}({street} in {city})>".format( cls=self.__class__.__name__, street=self.street, city=self.city_name, @@ -162,8 +162,8 @@ class Address(meta.Base): `.city.map` for convenience in interactive usage """ defaults = { - 'color': f'{config.NEUTRAL_COLOR}', - 'popup': f'{self.street}, {self.zip_code} {self.city_name}', + "color": f"{config.NEUTRAL_COLOR}", + "popup": f"{self.street}, {self.zip_code} {self.city_name}", } defaults.update(kwargs) diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index f6aef0b..b23847d 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -36,7 +36,7 @@ class Path(meta.Base): https://docs.sqlalchemy.org/en/stable/orm/basic_relationships.html#association-object # noqa:E501 """ - __tablename__ = 'addresses_addresses' + __tablename__ = "addresses_addresses" # Columns first_address_id = sa.Column(sa.Integer, primary_key=True) @@ -48,56 +48,56 @@ class Path(meta.Base): # The duration is measured in seconds. bicycle_duration = sa.Column(sa.Integer, nullable=True) # An array of latitude-longitude pairs approximating a courier's way. - _directions = sa.Column('directions', postgresql.JSON, nullable=True) + _directions = sa.Column("directions", postgresql.JSON, nullable=True) # Constraints __table_args__ = ( # The two `Address` objects must be in the same `.city`. sa.ForeignKeyConstraint( - ['first_address_id', 'city_id'], - ['addresses.id', 'addresses.city_id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["first_address_id", "city_id"], + ["addresses.id", "addresses.city_id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['second_address_id', 'city_id'], - ['addresses.id', 'addresses.city_id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["second_address_id", "city_id"], + ["addresses.id", "addresses.city_id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), # Each `Address`-`Address` pair only has one distance. - sa.UniqueConstraint('first_address_id', 'second_address_id'), + sa.UniqueConstraint("first_address_id", "second_address_id"), sa.CheckConstraint( - 'first_address_id < second_address_id', - name='distances_are_symmetric_for_bicycles', + "first_address_id < second_address_id", + name="distances_are_symmetric_for_bicycles", ), sa.CheckConstraint( - '0 <= air_distance AND air_distance < 20000', - name='realistic_air_distance', + "0 <= air_distance AND air_distance < 20000", + name="realistic_air_distance", ), sa.CheckConstraint( - 'bicycle_distance < 25000', # `.bicycle_distance` may not be negative - name='realistic_bicycle_distance', # due to the constraint below. + "bicycle_distance < 25000", # `.bicycle_distance` may not be negative + name="realistic_bicycle_distance", # due to the constraint below. ), sa.CheckConstraint( - 'air_distance <= bicycle_distance', - name='air_distance_is_shortest', + "air_distance <= bicycle_distance", + name="air_distance_is_shortest", ), sa.CheckConstraint( - '0 <= bicycle_duration AND bicycle_duration <= 3600', - name='realistic_bicycle_travel_time', + "0 <= bicycle_duration AND bicycle_duration <= 3600", + name="realistic_bicycle_travel_time", ), ) # Relationships first_address = orm.relationship( - 'Address', - foreign_keys='[Path.first_address_id, Path.city_id]', + "Address", + foreign_keys="[Path.first_address_id, Path.city_id]", ) second_address = orm.relationship( - 'Address', - foreign_keys='[Path.second_address_id, Path.city_id]', - overlaps='first_address', + "Address", + foreign_keys="[Path.second_address_id, Path.city_id]", + overlaps="first_address", ) @classmethod @@ -202,28 +202,28 @@ class Path(meta.Base): response = client.directions( origin=self.first_address.location.lat_lng, destination=self.second_address.location.lat_lng, - mode='bicycling', + mode="bicycling", alternatives=False, ) # Without "alternatives" and "waypoints", the `response` contains # exactly one "route" that consists of exactly one "leg". # Source: https://developers.google.com/maps/documentation/directions/get-directions#Legs # noqa:E501 - route = response[0]['legs'][0] + route = response[0]["legs"][0] - self.bicycle_distance = route['distance']['value'] - self.bicycle_duration = route['duration']['value'] + self.bicycle_distance = route["distance"]["value"] + self.bicycle_duration = route["duration"]["value"] # Each route consists of many "steps" that are instructions as to how to # get from A to B. As a step's "start_location" may equal the previous step's # "end_location", we use an `OrderedSet` to find the unique latitude-longitude # pairs that make up the path from `.first_address` to `.second_address`. steps: ordered_set.OrderedSet[Tuple[float, float]] = ordered_set.OrderedSet() - for step in route['steps']: + for step in route["steps"]: steps.add( - (step['start_location']['lat'], step['start_location']['lng']), + (step["start_location"]["lat"], step["start_location"]["lng"]), ) steps.add( - (step['end_location']['lat'], step['end_location']['lng']), + (step["end_location"]["lat"], step["end_location"]["lng"]), ) steps.discard(self.first_address.location.lat_lng) @@ -258,11 +258,11 @@ class Path(meta.Base): self, *, reverse: bool = False, - start_tooltip: str = 'Start', - end_tooltip: str = 'End', - start_color: str = 'green', - end_color: str = 'red', - path_color: str = 'black', + start_tooltip: str = "Start", + end_tooltip: str = "End", + start_color: str = "green", + end_color: str = "red", + path_color: str = "black", ) -> folium.Map: # pragma: no cover """Draw the `.waypoints` from `.first_address` to `.second_address`. diff --git a/src/velofy/db/addresses_pixels.py b/src/velofy/db/addresses_pixels.py index 2612de4..7736b90 100644 --- a/src/velofy/db/addresses_pixels.py +++ b/src/velofy/db/addresses_pixels.py @@ -16,7 +16,7 @@ class AddressPixelAssociation(meta.Base): https://docs.sqlalchemy.org/en/stable/orm/basic_relationships.html#association-object # noqa:E501 """ - __tablename__ = 'addresses_pixels' + __tablename__ = "addresses_pixels" # Columns address_id = sa.Column(sa.Integer, primary_key=True) @@ -28,29 +28,29 @@ class AddressPixelAssociation(meta.Base): __table_args__ = ( # An `Address` can only be on a `Grid` ... sa.ForeignKeyConstraint( - ['address_id', 'city_id'], - ['addresses.id', 'addresses.city_id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["address_id", "city_id"], + ["addresses.id", "addresses.city_id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), # ... if their `.city` attributes match. sa.ForeignKeyConstraint( - ['grid_id', 'city_id'], - ['grids.id', 'grids.city_id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["grid_id", "city_id"], + ["grids.id", "grids.city_id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), # Each `Address` can only be on a `Grid` once. - sa.UniqueConstraint('address_id', 'grid_id'), + sa.UniqueConstraint("address_id", "grid_id"), # An association must reference an existing `Grid`-`Pixel` pair. sa.ForeignKeyConstraint( - ['pixel_id', 'grid_id'], - ['pixels.id', 'pixels.grid_id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["pixel_id", "grid_id"], + ["pixels.id", "pixels.grid_id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), ) # Relationships - address = orm.relationship('Address', back_populates='pixels') - pixel = orm.relationship('Pixel', back_populates='addresses') + address = orm.relationship("Address", back_populates="pixels") + pixel = orm.relationship("Pixel", back_populates="addresses") diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index 47d3a29..46e1b19 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -18,7 +18,7 @@ from velofy.db import utils class City(meta.Base): """A city where the UDP operates in.""" - __tablename__ = 'cities' + __tablename__ = "cities" # Generic columns id = sa.Column( @@ -39,16 +39,16 @@ class City(meta.Base): initial_zoom = sa.Column(sa.SmallInteger, nullable=False) # Relationships - addresses = orm.relationship('Address', back_populates='city') - grids = orm.relationship('Grid', back_populates='city') - replays = orm.relationship('ReplaySimulation', back_populates='city') + addresses = orm.relationship("Address", back_populates="city") + grids = orm.relationship("Grid", back_populates="city") + replays = orm.relationship("ReplaySimulation", back_populates="city") # We do not implement a `.__init__()` method and use SQLAlchemy's default. # The uninitialized attribute `._map` is computed on the fly. note:d334120ei def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}({name})>'.format(cls=self.__class__.__name__, name=self.name) + return "<{cls}({name})>".format(cls=self.__class__.__name__, name=self.name) @functools.cached_property def center(self) -> utils.Location: @@ -115,7 +115,7 @@ class City(meta.Base): See docstring for `.clear_map()` for further info. """ - if not hasattr(self, '_map'): # note:d334120e + if not hasattr(self, "_map"): # note:d334120e self.clear_map() return self._map @@ -157,10 +157,10 @@ class City(meta.Base): .all() ) if len(restaurants) == 1: - tooltip = f'{restaurants[0].name} (#{restaurants[0].id})' + tooltip = f"{restaurants[0].name} (#{restaurants[0].id})" else: - tooltip = 'Restaurants ' + ', '.join( - f'#{restaurant.id}' for restaurant in restaurants + tooltip = "Restaurants " + ", ".join( + f"#{restaurant.id}" for restaurant in restaurants ) if order_counts: @@ -183,7 +183,7 @@ class City(meta.Base): else: radius = 1 - tooltip += f' | n_orders={n_orders}' + tooltip += f" | n_orders={n_orders}" address.draw( radius=radius, diff --git a/src/velofy/db/connection.py b/src/velofy/db/connection.py index 161b3e9..467a0bc 100644 --- a/src/velofy/db/connection.py +++ b/src/velofy/db/connection.py @@ -16,7 +16,7 @@ from sqlalchemy import orm import velofy -if os.getenv('TESTING'): +if os.getenv("TESTING"): # Specify the types explicitly to make mypy happy. engine: engine_mod.Engine = None connection: engine_mod.Connection = None diff --git a/src/velofy/db/couriers.py b/src/velofy/db/couriers.py index 5ea42bc..13fc8dc 100644 --- a/src/velofy/db/couriers.py +++ b/src/velofy/db/couriers.py @@ -10,13 +10,13 @@ from velofy.db import meta class Courier(meta.Base): """A courier working for the UDP.""" - __tablename__ = 'couriers' + __tablename__ = "couriers" # Columns id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) created_at = sa.Column(sa.DateTime, nullable=False) vehicle = sa.Column(sa.Unicode(length=10), nullable=False) - historic_speed = sa.Column('speed', postgresql.DOUBLE_PRECISION, nullable=False) + historic_speed = sa.Column("speed", postgresql.DOUBLE_PRECISION, nullable=False) capacity = sa.Column(sa.SmallInteger, nullable=False) pay_per_hour = sa.Column(sa.SmallInteger, nullable=False) pay_per_order = sa.Column(sa.SmallInteger, nullable=False) @@ -25,29 +25,29 @@ class Courier(meta.Base): __table_args__ = ( sa.CheckConstraint( "vehicle IN ('bicycle', 'motorcycle')", - name='available_vehicle_types', + name="available_vehicle_types", ), - sa.CheckConstraint('0 <= speed AND speed <= 30', name='realistic_speed'), + sa.CheckConstraint("0 <= speed AND speed <= 30", name="realistic_speed"), sa.CheckConstraint( - '0 <= capacity AND capacity <= 200', - name='capacity_under_200_liters', + "0 <= capacity AND capacity <= 200", + name="capacity_under_200_liters", ), sa.CheckConstraint( - '0 <= pay_per_hour AND pay_per_hour <= 1500', - name='realistic_pay_per_hour', + "0 <= pay_per_hour AND pay_per_hour <= 1500", + name="realistic_pay_per_hour", ), sa.CheckConstraint( - '0 <= pay_per_order AND pay_per_order <= 650', - name='realistic_pay_per_order', + "0 <= pay_per_order AND pay_per_order <= 650", + name="realistic_pay_per_order", ), ) # Relationships - orders = orm.relationship('Order', back_populates='courier') + orders = orm.relationship("Order", back_populates="courier") def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}(#{courier_id})>'.format( + return "<{cls}(#{courier_id})>".format( cls=self.__class__.__name__, courier_id=self.id, ) diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index 72d165b..e0317f2 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -14,20 +14,20 @@ from velofy.db import meta class Customer(meta.Base): """A customer of the UDP.""" - __tablename__ = 'customers' + __tablename__ = "customers" # Columns id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}(#{customer_id})>'.format( + return "<{cls}(#{customer_id})>".format( cls=self.__class__.__name__, customer_id=self.id, ) # Relationships - orders = orm.relationship('Order', back_populates='customer') + orders = orm.relationship("Order", back_populates="customer") def clear_map(self) -> Customer: # pragma: no cover """Shortcut to the `...city.clear_map()` method. @@ -108,7 +108,7 @@ class Customer(meta.Base): color=config.CUSTOMER_COLOR, fill_color=config.CUSTOMER_COLOR, fill_opacity=0.3, - tooltip=f'n_orders={n_orders}', + tooltip=f"n_orders={n_orders}", ) else: @@ -144,11 +144,11 @@ class Customer(meta.Base): ) if len(restaurants) == 1: # type:ignore tooltip = ( - f'{restaurants[0].name} (#{restaurants[0].id})' # type:ignore + f"{restaurants[0].name} (#{restaurants[0].id})" # type:ignore ) else: - tooltip = 'Restaurants ' + ', '.join( - f'#{restaurant.id}' for restaurant in restaurants # type:ignore + tooltip = "Restaurants " + ", ".join( + f"#{restaurant.id}" for restaurant in restaurants # type:ignore ) if order_counts: @@ -170,7 +170,7 @@ class Customer(meta.Base): else: radius = 1 - tooltip += f' | n_orders={n_orders}' + tooltip += f" | n_orders={n_orders}" address.draw( radius=radius, diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index b9cf193..7413e34 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -20,7 +20,7 @@ class Forecast(meta.Base): the `.model` and `.actual` hold redundant values. """ - __tablename__ = 'forecasts' + __tablename__ = "forecasts" # Columns id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) @@ -46,10 +46,10 @@ class Forecast(meta.Base): # Constraints __table_args__ = ( sa.ForeignKeyConstraint( - ['pixel_id'], - ['pixels.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["pixel_id"], + ["pixels.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.CheckConstraint( """ @@ -59,26 +59,26 @@ class Forecast(meta.Base): EXTRACT(HOUR FROM start_at) > 22 ) """, - name='start_at_must_be_within_operating_hours', + name="start_at_must_be_within_operating_hours", ), sa.CheckConstraint( - 'CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0', - name='start_at_minutes_must_be_quarters_of_the_hour', + "CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0", + name="start_at_minutes_must_be_quarters_of_the_hour", ), sa.CheckConstraint( - 'EXTRACT(SECONDS FROM start_at) = 0', - name='start_at_allows_no_seconds', + "EXTRACT(SECONDS FROM start_at) = 0", + name="start_at_allows_no_seconds", ), sa.CheckConstraint( - 'CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0', - name='start_at_allows_no_microseconds', + "CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0", + name="start_at_allows_no_microseconds", ), - sa.CheckConstraint('time_step > 0', name='time_step_must_be_positive'), + sa.CheckConstraint("time_step > 0", name="time_step_must_be_positive"), sa.CheckConstraint( - 'train_horizon > 0', - name='training_horizon_must_be_positive', + "train_horizon > 0", + name="training_horizon_must_be_positive", ), - sa.CheckConstraint('actual >= 0', name='actuals_must_be_non_negative'), + sa.CheckConstraint("actual >= 0", name="actuals_must_be_non_negative"), sa.CheckConstraint( """ NOT ( @@ -91,7 +91,7 @@ class Forecast(meta.Base): low95 IS NOT NULL AND high95 IS NULL ) """, - name='ci_upper_and_lower_bounds', + name="ci_upper_and_lower_bounds", ), sa.CheckConstraint( """ @@ -105,7 +105,7 @@ class Forecast(meta.Base): prediction > high95 ) """, - name='prediction_must_be_within_ci', + name="prediction_must_be_within_ci", ), sa.CheckConstraint( """ @@ -115,7 +115,7 @@ class Forecast(meta.Base): low95 > high95 ) """, - name='ci_upper_bound_greater_than_lower_bound', + name="ci_upper_bound_greater_than_lower_bound", ), sa.CheckConstraint( """ @@ -125,24 +125,24 @@ class Forecast(meta.Base): high80 > high95 ) """, - name='ci95_must_be_wider_than_ci80', + name="ci95_must_be_wider_than_ci80", ), # There can be only one prediction per forecasting setting. sa.UniqueConstraint( - 'pixel_id', - 'start_at', - 'time_step', - 'train_horizon', - 'model', + "pixel_id", + "start_at", + "time_step", + "train_horizon", + "model", ), ) # Relationships - pixel = orm.relationship('Pixel', back_populates='forecasts') + pixel = orm.relationship("Pixel", back_populates="forecasts") def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}: {prediction} for pixel ({n_x}|{n_y}) at {start_at}>'.format( + return "<{cls}: {prediction} for pixel ({n_x}|{n_y}) at {start_at}>".format( cls=self.__class__.__name__, prediction=self.prediction, n_x=self.pixel.n_x, @@ -187,16 +187,16 @@ class Forecast(meta.Base): for timestamp_idx in data.index: start_at = timestamp_idx.to_pydatetime() - actual = int(data.loc[timestamp_idx, 'actual']) - prediction = float(round(data.loc[timestamp_idx, 'prediction'], 5)) + actual = int(data.loc[timestamp_idx, "actual"]) + prediction = float(round(data.loc[timestamp_idx, "prediction"], 5)) # Explicit type casting. SQLAlchemy does not convert # `float('NaN')`s into plain `None`s. - low80 = data.loc[timestamp_idx, 'low80'] - high80 = data.loc[timestamp_idx, 'high80'] - low95 = data.loc[timestamp_idx, 'low95'] - high95 = data.loc[timestamp_idx, 'high95'] + low80 = data.loc[timestamp_idx, "low80"] + high80 = data.loc[timestamp_idx, "high80"] + low95 = data.loc[timestamp_idx, "low95"] + high95 = data.loc[timestamp_idx, "high95"] if math.isnan(low80): low80 = None diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index df362eb..15b77d1 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -19,7 +19,7 @@ class Grid(meta.Base): That is configures via the `Grid.side_length` attribute. """ - __tablename__ = 'grids' + __tablename__ = "grids" # Columns id = sa.Column( @@ -33,25 +33,25 @@ class Grid(meta.Base): # Constraints __table_args__ = ( sa.ForeignKeyConstraint( - ['city_id'], - ['cities.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["city_id"], + ["cities.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), # Each `Grid`, characterized by its `.side_length`, # may only exists once for a given `.city`. - sa.UniqueConstraint('city_id', 'side_length'), + sa.UniqueConstraint("city_id", "side_length"), # Needed by a `ForeignKeyConstraint` in `address_pixel_association`. - sa.UniqueConstraint('id', 'city_id'), + sa.UniqueConstraint("id", "city_id"), ) # Relationships - city = orm.relationship('City', back_populates='grids') - pixels = orm.relationship('Pixel', back_populates='grid') + city = orm.relationship("City", back_populates="grids") + pixels = orm.relationship("Pixel", back_populates="grid") def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}: {area} sqr. km>'.format( + return "<{cls}: {area} sqr. km>".format( cls=self.__class__.__name__, area=self.pixel_area, ) diff --git a/src/velofy/db/meta.py b/src/velofy/db/meta.py index b4e1506..ff86eb2 100644 --- a/src/velofy/db/meta.py +++ b/src/velofy/db/meta.py @@ -12,11 +12,11 @@ Base: Any = orm.declarative_base( metadata=sa.MetaData( schema=velofy.config.CLEAN_SCHEMA, naming_convention={ - 'pk': 'pk_%(table_name)s', - 'fk': 'fk_%(table_name)s_to_%(referred_table_name)s_via_%(column_0_N_name)s', # noqa:E501 - 'uq': 'uq_%(table_name)s_on_%(column_0_N_name)s', - 'ix': 'ix_%(table_name)s_on_%(column_0_N_name)s', - 'ck': 'ck_%(table_name)s_on_%(constraint_name)s', + "pk": "pk_%(table_name)s", + "fk": "fk_%(table_name)s_to_%(referred_table_name)s_via_%(column_0_N_name)s", # noqa:E501 + "uq": "uq_%(table_name)s_on_%(column_0_N_name)s", + "ix": "ix_%(table_name)s_on_%(column_0_N_name)s", + "ck": "ck_%(table_name)s_on_%(constraint_name)s", }, ), ) diff --git a/src/velofy/db/orders.py b/src/velofy/db/orders.py index f0723d0..897c2ea 100644 --- a/src/velofy/db/orders.py +++ b/src/velofy/db/orders.py @@ -15,11 +15,11 @@ from velofy.db import meta class Order(meta.Base): """An order by a `Customer` of the UDP.""" - __tablename__ = 'orders' + __tablename__ = "orders" # Generic columns id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) - _delivery_id = sa.Column('delivery_id', sa.Integer, index=True, unique=True) + _delivery_id = sa.Column("delivery_id", sa.Integer, index=True, unique=True) customer_id = sa.Column(sa.Integer, nullable=False, index=True) placed_at = sa.Column(sa.DateTime, nullable=False, index=True) ad_hoc = sa.Column(sa.Boolean, nullable=False) @@ -70,7 +70,7 @@ class Order(meta.Base): delivery_at = sa.Column(sa.DateTime) delivery_at_corrected = sa.Column(sa.Boolean, index=True) delivery_not_confirmed = sa.Column(sa.Boolean) - _courier_waited_at_delivery = sa.Column('courier_waited_at_delivery', sa.Boolean) + _courier_waited_at_delivery = sa.Column("courier_waited_at_delivery", sa.Boolean) # Statistical columns logged_delivery_distance = sa.Column(sa.SmallInteger, nullable=True) @@ -80,46 +80,46 @@ class Order(meta.Base): # Constraints __table_args__ = ( sa.ForeignKeyConstraint( - ['customer_id'], - ['customers.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["customer_id"], + ["customers.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['courier_id'], - ['couriers.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["courier_id"], + ["couriers.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['pickup_address_id'], - ['addresses.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["pickup_address_id"], + ["addresses.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( # This foreign key ensures that there is only # one `.pickup_address` per `.restaurant` - ['restaurant_id', 'pickup_address_id'], - ['restaurants.id', 'restaurants.address_id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["restaurant_id", "pickup_address_id"], + ["restaurants.id", "restaurants.address_id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['delivery_address_id'], - ['addresses.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["delivery_address_id"], + ["addresses.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), # Needed by a `ForeignKeyConstraint` in `ReplayedOrder`. - sa.UniqueConstraint('id', 'ad_hoc'), + sa.UniqueConstraint("id", "ad_hoc"), sa.CheckConstraint( """ (ad_hoc IS TRUE AND scheduled_delivery_at IS NULL) OR (ad_hoc IS FALSE AND scheduled_delivery_at IS NOT NULL) """, - name='either_ad_hoc_or_scheduled_order', + name="either_ad_hoc_or_scheduled_order", ), sa.CheckConstraint( """ @@ -132,7 +132,7 @@ class Order(meta.Base): ) ) """, - name='ad_hoc_orders_within_business_hours', + name="ad_hoc_orders_within_business_hours", ), sa.CheckConstraint( """ @@ -153,7 +153,7 @@ class Order(meta.Base): ) ) """, - name='scheduled_orders_within_business_hours', + name="scheduled_orders_within_business_hours", ), sa.CheckConstraint( """ @@ -167,7 +167,7 @@ class Order(meta.Base): = 0 ) """, - name='scheduled_orders_must_be_at_quarters_of_an_hour', + name="scheduled_orders_must_be_at_quarters_of_an_hour", ), sa.CheckConstraint( """ @@ -175,7 +175,7 @@ class Order(meta.Base): EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800 ) """, - name='scheduled_orders_not_within_30_minutes', + name="scheduled_orders_not_within_30_minutes", ), sa.CheckConstraint( """ @@ -185,7 +185,7 @@ class Order(meta.Base): cancelled_at IS NOT NULL ) """, - name='only_cancelled_orders_may_have_cancelled_at', + name="only_cancelled_orders_may_have_cancelled_at", ), sa.CheckConstraint( """ @@ -195,27 +195,27 @@ class Order(meta.Base): delivery_at IS NOT NULL ) """, - name='cancelled_orders_must_not_be_delivered', + name="cancelled_orders_must_not_be_delivered", ), sa.CheckConstraint( - '0 <= estimated_prep_duration AND estimated_prep_duration <= 2700', - name='estimated_prep_duration_between_0_and_2700', + "0 <= estimated_prep_duration AND estimated_prep_duration <= 2700", + name="estimated_prep_duration_between_0_and_2700", ), sa.CheckConstraint( - 'estimated_prep_duration % 60 = 0', - name='estimated_prep_duration_must_be_whole_minutes', + "estimated_prep_duration % 60 = 0", + name="estimated_prep_duration_must_be_whole_minutes", ), sa.CheckConstraint( - '0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900', - name='estimated_prep_buffer_between_0_and_900', + "0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900", + name="estimated_prep_buffer_between_0_and_900", ), sa.CheckConstraint( - 'estimated_prep_buffer % 60 = 0', - name='estimated_prep_buffer_must_be_whole_minutes', + "estimated_prep_buffer % 60 = 0", + name="estimated_prep_buffer_must_be_whole_minutes", ), sa.CheckConstraint( - '0 <= utilization AND utilization <= 100', - name='utilization_between_0_and_100', + "0 <= utilization AND utilization <= 100", + name="utilization_between_0_and_100", ), *( sa.CheckConstraint( @@ -226,21 +226,21 @@ class Order(meta.Base): OR ({column} IS NOT NULL AND {column}_corrected IS NOT NULL) """, - name=f'corrections_only_for_set_value_{index}', + name=f"corrections_only_for_set_value_{index}", ) for index, column in enumerate( ( - 'scheduled_delivery_at', - 'cancelled_at', - 'restaurant_notified_at', - 'restaurant_confirmed_at', - 'estimated_prep_duration', - 'dispatch_at', - 'courier_notified_at', - 'courier_accepted_at', - 'pickup_at', - 'left_pickup_at', - 'delivery_at', + "scheduled_delivery_at", + "cancelled_at", + "restaurant_notified_at", + "restaurant_confirmed_at", + "estimated_prep_duration", + "dispatch_at", + "courier_notified_at", + "courier_accepted_at", + "pickup_at", + "left_pickup_at", + "delivery_at", ), ) ), @@ -251,9 +251,9 @@ class Order(meta.Base): OR ({event}_at IS NOT NULL AND {event}_not_confirmed IS NOT NULL) """, - name=f'{event}_not_confirmed_only_if_{event}', + name=f"{event}_not_confirmed_only_if_{event}", ) - for event in ('pickup', 'delivery') + for event in ("pickup", "delivery") ), sa.CheckConstraint( """ @@ -261,92 +261,92 @@ class Order(meta.Base): OR (delivery_at IS NOT NULL AND courier_waited_at_delivery IS NOT NULL) """, - name='courier_waited_at_delivery_only_if_delivery', + name="courier_waited_at_delivery_only_if_delivery", ), *( sa.CheckConstraint( constraint, - name='ordered_timestamps_{index}'.format(index=index), + name="ordered_timestamps_{index}".format(index=index), ) for index, constraint in enumerate( ( - 'placed_at < scheduled_delivery_at', - 'placed_at < first_estimated_delivery_at', - 'placed_at < cancelled_at', - 'placed_at < restaurant_notified_at', - 'placed_at < restaurant_confirmed_at', - 'placed_at < dispatch_at', - 'placed_at < courier_notified_at', - 'placed_at < courier_accepted_at', - 'placed_at < reached_pickup_at', - 'placed_at < pickup_at', - 'placed_at < left_pickup_at', - 'placed_at < reached_delivery_at', - 'placed_at < delivery_at', - 'cancelled_at > restaurant_notified_at', - 'cancelled_at > restaurant_confirmed_at', - 'cancelled_at > dispatch_at', - 'cancelled_at > courier_notified_at', - 'cancelled_at > courier_accepted_at', - 'cancelled_at > reached_pickup_at', - 'cancelled_at > pickup_at', - 'cancelled_at > left_pickup_at', - 'cancelled_at > reached_delivery_at', - 'restaurant_notified_at < restaurant_confirmed_at', - 'restaurant_notified_at < pickup_at', - 'restaurant_confirmed_at < pickup_at', - 'dispatch_at < courier_notified_at', - 'dispatch_at < courier_accepted_at', - 'dispatch_at < reached_pickup_at', - 'dispatch_at < pickup_at', - 'dispatch_at < left_pickup_at', - 'dispatch_at < reached_delivery_at', - 'dispatch_at < delivery_at', - 'courier_notified_at < courier_accepted_at', - 'courier_notified_at < reached_pickup_at', - 'courier_notified_at < pickup_at', - 'courier_notified_at < left_pickup_at', - 'courier_notified_at < reached_delivery_at', - 'courier_notified_at < delivery_at', - 'courier_accepted_at < reached_pickup_at', - 'courier_accepted_at < pickup_at', - 'courier_accepted_at < left_pickup_at', - 'courier_accepted_at < reached_delivery_at', - 'courier_accepted_at < delivery_at', - 'reached_pickup_at < pickup_at', - 'reached_pickup_at < left_pickup_at', - 'reached_pickup_at < reached_delivery_at', - 'reached_pickup_at < delivery_at', - 'pickup_at < left_pickup_at', - 'pickup_at < reached_delivery_at', - 'pickup_at < delivery_at', - 'left_pickup_at < reached_delivery_at', - 'left_pickup_at < delivery_at', - 'reached_delivery_at < delivery_at', + "placed_at < scheduled_delivery_at", + "placed_at < first_estimated_delivery_at", + "placed_at < cancelled_at", + "placed_at < restaurant_notified_at", + "placed_at < restaurant_confirmed_at", + "placed_at < dispatch_at", + "placed_at < courier_notified_at", + "placed_at < courier_accepted_at", + "placed_at < reached_pickup_at", + "placed_at < pickup_at", + "placed_at < left_pickup_at", + "placed_at < reached_delivery_at", + "placed_at < delivery_at", + "cancelled_at > restaurant_notified_at", + "cancelled_at > restaurant_confirmed_at", + "cancelled_at > dispatch_at", + "cancelled_at > courier_notified_at", + "cancelled_at > courier_accepted_at", + "cancelled_at > reached_pickup_at", + "cancelled_at > pickup_at", + "cancelled_at > left_pickup_at", + "cancelled_at > reached_delivery_at", + "restaurant_notified_at < restaurant_confirmed_at", + "restaurant_notified_at < pickup_at", + "restaurant_confirmed_at < pickup_at", + "dispatch_at < courier_notified_at", + "dispatch_at < courier_accepted_at", + "dispatch_at < reached_pickup_at", + "dispatch_at < pickup_at", + "dispatch_at < left_pickup_at", + "dispatch_at < reached_delivery_at", + "dispatch_at < delivery_at", + "courier_notified_at < courier_accepted_at", + "courier_notified_at < reached_pickup_at", + "courier_notified_at < pickup_at", + "courier_notified_at < left_pickup_at", + "courier_notified_at < reached_delivery_at", + "courier_notified_at < delivery_at", + "courier_accepted_at < reached_pickup_at", + "courier_accepted_at < pickup_at", + "courier_accepted_at < left_pickup_at", + "courier_accepted_at < reached_delivery_at", + "courier_accepted_at < delivery_at", + "reached_pickup_at < pickup_at", + "reached_pickup_at < left_pickup_at", + "reached_pickup_at < reached_delivery_at", + "reached_pickup_at < delivery_at", + "pickup_at < left_pickup_at", + "pickup_at < reached_delivery_at", + "pickup_at < delivery_at", + "left_pickup_at < reached_delivery_at", + "left_pickup_at < delivery_at", + "reached_delivery_at < delivery_at", ), ) ), ) # Relationships - customer = orm.relationship('Customer', back_populates='orders') + customer = orm.relationship("Customer", back_populates="orders") restaurant = orm.relationship( - 'Restaurant', - back_populates='orders', - primaryjoin='Restaurant.id == Order.restaurant_id', + "Restaurant", + back_populates="orders", + primaryjoin="Restaurant.id == Order.restaurant_id", ) - courier = orm.relationship('Courier', back_populates='orders') + courier = orm.relationship("Courier", back_populates="orders") pickup_address = orm.relationship( - 'Address', - back_populates='orders_picked_up', - foreign_keys='[Order.pickup_address_id]', + "Address", + back_populates="orders_picked_up", + foreign_keys="[Order.pickup_address_id]", ) delivery_address = orm.relationship( - 'Address', - back_populates='orders_delivered', - foreign_keys='[Order.delivery_address_id]', + "Address", + back_populates="orders_delivered", + foreign_keys="[Order.delivery_address_id]", ) - replays = orm.relationship('ReplayedOrder', back_populates='actual') + replays = orm.relationship("ReplayedOrder", back_populates="actual") # Convenience properties @@ -385,9 +385,9 @@ class Order(meta.Base): This measures the time it took the UDP to notify the `.courier` after dispatch. """ if not self.dispatch_at: - raise RuntimeError('dispatch_at is not set') + raise RuntimeError("dispatch_at is not set") if not self.courier_accepted_at: - raise RuntimeError('courier_accepted_at is not set') + raise RuntimeError("courier_accepted_at is not set") return self.courier_accepted_at - self.dispatch_at @property @@ -397,36 +397,36 @@ class Order(meta.Base): A subset of `.time_to_accept`. """ if not self.courier_notified_at: - raise RuntimeError('courier_notified_at is not set') + raise RuntimeError("courier_notified_at is not set") if not self.courier_accepted_at: - raise RuntimeError('courier_accepted_at is not set') + raise RuntimeError("courier_accepted_at is not set") return self.courier_accepted_at - self.courier_notified_at @property def time_to_pickup(self) -> datetime.timedelta: """Time from the `.courier`'s acceptance to arrival at `.pickup_address`.""" if not self.courier_accepted_at: - raise RuntimeError('courier_accepted_at is not set') + raise RuntimeError("courier_accepted_at is not set") if not self.reached_pickup_at: - raise RuntimeError('reached_pickup_at is not set') + raise RuntimeError("reached_pickup_at is not set") return self.reached_pickup_at - self.courier_accepted_at @property def time_at_pickup(self) -> datetime.timedelta: """Time the `.courier` stayed at the `.pickup_address`.""" if not self.reached_pickup_at: - raise RuntimeError('reached_pickup_at is not set') + raise RuntimeError("reached_pickup_at is not set") if not self.pickup_at: - raise RuntimeError('pickup_at is not set') + raise RuntimeError("pickup_at is not set") return self.pickup_at - self.reached_pickup_at @property def scheduled_pickup_at(self) -> datetime.datetime: """Point in time at which the pickup was scheduled.""" if not self.restaurant_notified_at: - raise RuntimeError('restaurant_notified_at is not set') + raise RuntimeError("restaurant_notified_at is not set") if not self.estimated_prep_duration: - raise RuntimeError('estimated_prep_duration is not set') + raise RuntimeError("estimated_prep_duration is not set") delta = datetime.timedelta(seconds=self.estimated_prep_duration) return self.restaurant_notified_at + delta @@ -488,18 +488,18 @@ class Order(meta.Base): def time_to_delivery(self) -> datetime.timedelta: """Time the `.courier` took from `.pickup_address` to `.delivery_address`.""" if not self.pickup_at: - raise RuntimeError('pickup_at is not set') + raise RuntimeError("pickup_at is not set") if not self.reached_delivery_at: - raise RuntimeError('reached_delivery_at is not set') + raise RuntimeError("reached_delivery_at is not set") return self.reached_delivery_at - self.pickup_at @property def time_at_delivery(self) -> datetime.timedelta: """Time the `.courier` stayed at the `.delivery_address`.""" if not self.reached_delivery_at: - raise RuntimeError('reached_delivery_at is not set') + raise RuntimeError("reached_delivery_at is not set") if not self.delivery_at: - raise RuntimeError('delivery_at is not set') + raise RuntimeError("delivery_at is not set") return self.delivery_at - self.reached_delivery_at @property @@ -520,7 +520,7 @@ class Order(meta.Base): Goes together with `.delivery_late`. """ if not self.scheduled: - raise AttributeError('Makes sense only for scheduled orders') + raise AttributeError("Makes sense only for scheduled orders") return max(datetime.timedelta(), self.scheduled_delivery_at - self.delivery_at) @property @@ -534,23 +534,23 @@ class Order(meta.Base): Goes together with `.delivery_early`. """ if not self.scheduled: - raise AttributeError('Makes sense only for scheduled orders') + raise AttributeError("Makes sense only for scheduled orders") return max(datetime.timedelta(), self.delivery_at - self.scheduled_delivery_at) @property def total_time(self) -> datetime.timedelta: """Time from order placement to delivery for an `.ad_hoc` order.""" if self.scheduled: - raise AttributeError('Scheduled orders have no total_time') + raise AttributeError("Scheduled orders have no total_time") if self.cancelled: - raise RuntimeError('Cancelled orders have no total_time') + raise RuntimeError("Cancelled orders have no total_time") return self.delivery_at - self.placed_at # Other Methods def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}(#{order_id})>'.format( + return "<{cls}(#{order_id})>".format( cls=self.__class__.__name__, order_id=self.id, ) @@ -566,8 +566,8 @@ class Order(meta.Base): """ path = db.Path.from_order(self) - restaurant_tooltip = f'{self.restaurant.name} (#{self.restaurant.id})' - customer_tooltip = f'Customer #{self.customer.id}' + restaurant_tooltip = f"{self.restaurant.name} (#{self.restaurant.id})" + customer_tooltip = f"Customer #{self.customer.id}" # Because the underlying distance matrix is symmetric (i.e., a DB constraint), # we must check if the `.pickup_address` is the couriers' `Path`'s start. diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index 708e3e0..228ba29 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -25,7 +25,7 @@ class Pixel(meta.Base): Every `Pixel` has a unique `n_x`-`n_y` coordinate within the `Grid`. """ - __tablename__ = 'pixels' + __tablename__ = "pixels" # Columns id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) @@ -36,27 +36,27 @@ class Pixel(meta.Base): # Constraints __table_args__ = ( sa.ForeignKeyConstraint( - ['grid_id'], - ['grids.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["grid_id"], + ["grids.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), - sa.CheckConstraint('0 <= n_x', name='n_x_is_positive'), - sa.CheckConstraint('0 <= n_y', name='n_y_is_positive'), + sa.CheckConstraint("0 <= n_x", name="n_x_is_positive"), + sa.CheckConstraint("0 <= n_y", name="n_y_is_positive"), # Needed by a `ForeignKeyConstraint` in `AddressPixelAssociation`. - sa.UniqueConstraint('id', 'grid_id'), + sa.UniqueConstraint("id", "grid_id"), # Each coordinate within the same `grid` is used at most once. - sa.UniqueConstraint('grid_id', 'n_x', 'n_y'), + sa.UniqueConstraint("grid_id", "n_x", "n_y"), ) # Relationships - grid = orm.relationship('Grid', back_populates='pixels') - addresses = orm.relationship('AddressPixelAssociation', back_populates='pixel') - forecasts = orm.relationship('Forecast', back_populates='pixel') + grid = orm.relationship("Grid", back_populates="pixels") + addresses = orm.relationship("AddressPixelAssociation", back_populates="pixel") + forecasts = orm.relationship("Forecast", back_populates="pixel") def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}: ({x}|{y})>'.format( + return "<{cls}: ({x}|{y})>".format( cls=self.__class__.__name__, x=self.n_x, y=self.n_y, @@ -163,17 +163,17 @@ class Pixel(meta.Base): (self.southwest.latitude, self.southwest.longitude), (self.northeast.latitude, self.northeast.longitude), ) - info_text = f'Pixel({self.n_x}|{self.n_y})' + info_text = f"Pixel({self.n_x}|{self.n_y})" # Make the `Pixel`s look like a checkerboard. if (self.n_x + self.n_y) % 2: - color = '#808000' + color = "#808000" else: - color = '#ff8c00' + color = "#ff8c00" marker = folium.Rectangle( bounds=bounds, - color='gray', + color="gray", opacity=0.2, weight=5, fill_color=color, @@ -220,11 +220,11 @@ class Pixel(meta.Base): ) if len(restaurants) == 1: # type:ignore tooltip = ( - f'{restaurants[0].name} (#{restaurants[0].id})' # type:ignore + f"{restaurants[0].name} (#{restaurants[0].id})" # type:ignore ) else: - tooltip = 'Restaurants ' + ', '.join( - f'#{restaurant.id}' for restaurant in restaurants # type:ignore + tooltip = "Restaurants " + ", ".join( + f"#{restaurant.id}" for restaurant in restaurants # type:ignore ) if order_counts: @@ -247,7 +247,7 @@ class Pixel(meta.Base): else: radius = 1 - tooltip += f' | n_orders={n_orders}' + tooltip += f" | n_orders={n_orders}" address.draw( radius=radius, diff --git a/src/velofy/db/replay/orders.py b/src/velofy/db/replay/orders.py index 8219017..a61ec3a 100644 --- a/src/velofy/db/replay/orders.py +++ b/src/velofy/db/replay/orders.py @@ -11,7 +11,7 @@ from velofy.db import meta class ReplayedOrder(meta.Base): """A simulated order by a `Customer` of the UDP.""" - __tablename__ = 'replayed_orders' + __tablename__ = "replayed_orders" # Generic columns simulation_id = sa.Column(sa.Integer, primary_key=True) @@ -55,22 +55,22 @@ class ReplayedOrder(meta.Base): # Constraints __table_args__ = ( sa.ForeignKeyConstraint( - ['simulation_id'], - ['replay_simulations.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["simulation_id"], + ["replay_simulations.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['actual_order_id', 'ad_hoc'], - ['orders.id', 'orders.ad_hoc'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["actual_order_id", "ad_hoc"], + ["orders.id", "orders.ad_hoc"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.ForeignKeyConstraint( - ['courier_id'], - ['couriers.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["courier_id"], + ["couriers.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), # The check constraints model some of the assumptions made in the simulations. sa.CheckConstraint( @@ -90,7 +90,7 @@ class ReplayedOrder(meta.Base): scheduled_delivery_at IS NOT NULL ) """, - name='either_ad_hoc_or_scheduled_order', + name="either_ad_hoc_or_scheduled_order", ), sa.CheckConstraint( """ @@ -103,7 +103,7 @@ class ReplayedOrder(meta.Base): ) ) """, - name='ad_hoc_orders_within_business_hours', + name="ad_hoc_orders_within_business_hours", ), sa.CheckConstraint( """ @@ -124,7 +124,7 @@ class ReplayedOrder(meta.Base): ) ) """, - name='scheduled_orders_within_business_hours', + name="scheduled_orders_within_business_hours", ), sa.CheckConstraint( """ @@ -138,7 +138,7 @@ class ReplayedOrder(meta.Base): = 0 ) """, - name='scheduled_orders_must_be_at_quarters_of_an_hour', + name="scheduled_orders_must_be_at_quarters_of_an_hour", ), sa.CheckConstraint( """ @@ -146,7 +146,7 @@ class ReplayedOrder(meta.Base): EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800 ) """, - name='scheduled_orders_not_within_30_minutes', + name="scheduled_orders_not_within_30_minutes", ), sa.CheckConstraint( # A simulation must fill in at least all the timing and dispatch related @@ -187,7 +187,7 @@ class ReplayedOrder(meta.Base): delivery_at IS NOT NULL ) """, - name='orders_must_be_either_cancelled_or_fully_simulated', + name="orders_must_be_either_cancelled_or_fully_simulated", ), sa.CheckConstraint( # 23,487 out of the 660,608 orders were cancelled. In 685 of them, the @@ -224,28 +224,28 @@ class ReplayedOrder(meta.Base): delivery_at IS NOT NULL ) """, - name='cancellations_may_only_occur_before_pickup', + name="cancellations_may_only_occur_before_pickup", ), sa.CheckConstraint( # The actual `.estimated_prep_duration` and `.estimated_prep_buffer` # are modeled together as only one value. Therefore, the individual # upper limits of 2700 and 900 are added and result in 3600. - '0 <= estimated_prep_duration AND estimated_prep_duration <= 3600', - name='estimated_prep_duration_between_0_and_3600', + "0 <= estimated_prep_duration AND estimated_prep_duration <= 3600", + name="estimated_prep_duration_between_0_and_3600", ), sa.CheckConstraint( # We still round estimates of the preparation time to whole minutes. # Other estimates are unlikely to change the simulation results in # a significant way. - 'estimated_prep_duration % 60 = 0', - name='estimated_prep_duration_must_be_whole_minutes', + "estimated_prep_duration % 60 = 0", + name="estimated_prep_duration_must_be_whole_minutes", ), sa.CheckConstraint( # If a simulation's `.strategy` models `.utilization`, it must be # realistic. The value can be deduced from the actual order's # courier's `.capacity` and the actual order's `.utilization`. - '0 <= utilization AND utilization <= 100', - name='utilization_between_0_and_100', + "0 <= utilization AND utilization <= 100", + name="utilization_between_0_and_100", ), sa.CheckConstraint( # The UDP is open from 11 am to 11 pm. So, before 11 am there is no @@ -258,7 +258,7 @@ class ReplayedOrder(meta.Base): EXTRACT(HOUR FROM dispatch_at) < 11 ) """, - name='orders_dispatched_in_business_hours', + name="orders_dispatched_in_business_hours", ), *( # The timestamps must be in a logically correct order. That is the same as @@ -266,79 +266,79 @@ class ReplayedOrder(meta.Base): # and the non-simulated columns removed. sa.CheckConstraint( constraint, - name='ordered_timestamps_{index}'.format(index=index), + name="ordered_timestamps_{index}".format(index=index), ) for index, constraint in enumerate( ( - 'placed_at < scheduled_delivery_at', - 'placed_at < cancelled_at', - 'placed_at < restaurant_notified_at', - 'placed_at < restaurant_confirmed_at', - 'placed_at < restaurant_ready_at', - 'placed_at < dispatch_at', - 'placed_at < first_estimated_delivery_at', - 'placed_at < courier_notified_at', - 'placed_at < courier_accepted_at', - 'placed_at < reached_pickup_at', - 'placed_at < pickup_at', - 'placed_at < left_pickup_at', - 'placed_at < reached_delivery_at', - 'placed_at < delivery_at', - 'cancelled_at > restaurant_notified_at', - 'cancelled_at > restaurant_confirmed_at', - 'cancelled_at > restaurant_ready_at', - 'cancelled_at > dispatch_at', - 'cancelled_at > courier_notified_at', - 'cancelled_at > courier_accepted_at', - 'cancelled_at > reached_pickup_at', - 'restaurant_notified_at < restaurant_confirmed_at', - 'restaurant_notified_at < restaurant_ready_at', - 'restaurant_notified_at < pickup_at', - 'restaurant_confirmed_at < restaurant_ready_at', - 'restaurant_confirmed_at < pickup_at', - 'restaurant_ready_at < pickup_at', - 'dispatch_at < first_estimated_delivery_at', - 'dispatch_at < courier_notified_at', - 'dispatch_at < courier_accepted_at', - 'dispatch_at < reached_pickup_at', - 'dispatch_at < pickup_at', - 'dispatch_at < left_pickup_at', - 'dispatch_at < reached_delivery_at', - 'dispatch_at < delivery_at', - 'courier_notified_at < courier_accepted_at', - 'courier_notified_at < reached_pickup_at', - 'courier_notified_at < pickup_at', - 'courier_notified_at < left_pickup_at', - 'courier_notified_at < reached_delivery_at', - 'courier_notified_at < delivery_at', - 'courier_accepted_at < reached_pickup_at', - 'courier_accepted_at < pickup_at', - 'courier_accepted_at < left_pickup_at', - 'courier_accepted_at < reached_delivery_at', - 'courier_accepted_at < delivery_at', - 'reached_pickup_at < pickup_at', - 'reached_pickup_at < left_pickup_at', - 'reached_pickup_at < reached_delivery_at', - 'reached_pickup_at < delivery_at', - 'pickup_at < left_pickup_at', - 'pickup_at < reached_delivery_at', - 'pickup_at < delivery_at', - 'left_pickup_at < reached_delivery_at', - 'left_pickup_at < delivery_at', - 'reached_delivery_at < delivery_at', + "placed_at < scheduled_delivery_at", + "placed_at < cancelled_at", + "placed_at < restaurant_notified_at", + "placed_at < restaurant_confirmed_at", + "placed_at < restaurant_ready_at", + "placed_at < dispatch_at", + "placed_at < first_estimated_delivery_at", + "placed_at < courier_notified_at", + "placed_at < courier_accepted_at", + "placed_at < reached_pickup_at", + "placed_at < pickup_at", + "placed_at < left_pickup_at", + "placed_at < reached_delivery_at", + "placed_at < delivery_at", + "cancelled_at > restaurant_notified_at", + "cancelled_at > restaurant_confirmed_at", + "cancelled_at > restaurant_ready_at", + "cancelled_at > dispatch_at", + "cancelled_at > courier_notified_at", + "cancelled_at > courier_accepted_at", + "cancelled_at > reached_pickup_at", + "restaurant_notified_at < restaurant_confirmed_at", + "restaurant_notified_at < restaurant_ready_at", + "restaurant_notified_at < pickup_at", + "restaurant_confirmed_at < restaurant_ready_at", + "restaurant_confirmed_at < pickup_at", + "restaurant_ready_at < pickup_at", + "dispatch_at < first_estimated_delivery_at", + "dispatch_at < courier_notified_at", + "dispatch_at < courier_accepted_at", + "dispatch_at < reached_pickup_at", + "dispatch_at < pickup_at", + "dispatch_at < left_pickup_at", + "dispatch_at < reached_delivery_at", + "dispatch_at < delivery_at", + "courier_notified_at < courier_accepted_at", + "courier_notified_at < reached_pickup_at", + "courier_notified_at < pickup_at", + "courier_notified_at < left_pickup_at", + "courier_notified_at < reached_delivery_at", + "courier_notified_at < delivery_at", + "courier_accepted_at < reached_pickup_at", + "courier_accepted_at < pickup_at", + "courier_accepted_at < left_pickup_at", + "courier_accepted_at < reached_delivery_at", + "courier_accepted_at < delivery_at", + "reached_pickup_at < pickup_at", + "reached_pickup_at < left_pickup_at", + "reached_pickup_at < reached_delivery_at", + "reached_pickup_at < delivery_at", + "pickup_at < left_pickup_at", + "pickup_at < reached_delivery_at", + "pickup_at < delivery_at", + "left_pickup_at < reached_delivery_at", + "left_pickup_at < delivery_at", + "reached_delivery_at < delivery_at", ), ) ), ) # Relationships - simulation = orm.relationship('ReplaySimulation', back_populates='orders') - actual = orm.relationship('Order', back_populates='replays') - courier = orm.relationship('Courier') + simulation = orm.relationship("ReplaySimulation", back_populates="orders") + actual = orm.relationship("Order", back_populates="replays") + courier = orm.relationship("Courier") def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}(#{order_id})>'.format( + return "<{cls}(#{order_id})>".format( cls=self.__class__.__name__, order_id=self.actual.id, ) diff --git a/src/velofy/db/replay/simulations.py b/src/velofy/db/replay/simulations.py index c8caf4f..cada32a 100644 --- a/src/velofy/db/replay/simulations.py +++ b/src/velofy/db/replay/simulations.py @@ -12,7 +12,7 @@ class ReplaySimulation(meta.Base): ... for the orders as they arrived in reality. """ - __tablename__ = 'replay_simulations' + __tablename__ = "replay_simulations" # Columns id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) @@ -24,23 +24,23 @@ class ReplaySimulation(meta.Base): # Constraints __table_args__ = ( sa.ForeignKeyConstraint( - ['city_id'], - ['cities.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["city_id"], + ["cities.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), # A `.strategy` can be replayed several times per `.city`. - sa.UniqueConstraint('city_id', 'strategy', 'run'), - sa.CheckConstraint('run >= 0', name='run_is_a_count'), + sa.UniqueConstraint("city_id", "strategy", "run"), + sa.CheckConstraint("run >= 0", name="run_is_a_count"), ) # Relationships - city = orm.relationship('City', back_populates='replays') - orders = orm.relationship('ReplayedOrder', back_populates='simulation') + city = orm.relationship("City", back_populates="replays") + orders = orm.relationship("ReplayedOrder", back_populates="simulation") def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}({strategy} #{run} in {city})>'.format( + return "<{cls}({strategy} #{run} in {city})>".format( cls=self.__class__.__name__, strategy=self.strategy, run=self.run, diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 7e893e0..3dca5f0 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -19,7 +19,7 @@ class Restaurant(meta.Base): which in most cases is also the only one. """ - __tablename__ = 'restaurants' + __tablename__ = "restaurants" # Columns id = sa.Column( @@ -35,30 +35,30 @@ class Restaurant(meta.Base): # Constraints __table_args__ = ( sa.ForeignKeyConstraint( - ['address_id'], - ['addresses.id'], - onupdate='RESTRICT', - ondelete='RESTRICT', + ["address_id"], + ["addresses.id"], + onupdate="RESTRICT", + ondelete="RESTRICT", ), sa.CheckConstraint( - '0 <= estimated_prep_duration AND estimated_prep_duration <= 2400', - name='realistic_estimated_prep_duration', + "0 <= estimated_prep_duration AND estimated_prep_duration <= 2400", + name="realistic_estimated_prep_duration", ), # Needed by a `ForeignKeyConstraint` in `Order`. - sa.UniqueConstraint('id', 'address_id'), + sa.UniqueConstraint("id", "address_id"), ) # Relationships - address = orm.relationship('Address', back_populates='restaurants') + address = orm.relationship("Address", back_populates="restaurants") orders = orm.relationship( - 'Order', - back_populates='restaurant', - overlaps='orders_picked_up,pickup_address', + "Order", + back_populates="restaurant", + overlaps="orders_picked_up,pickup_address", ) def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}({name})>'.format(cls=self.__class__.__name__, name=self.name) + return "<{cls}({name})>".format(cls=self.__class__.__name__, name=self.name) def clear_map(self) -> Restaurant: # pragma: no cover """Shortcut to the `.address.city.clear_map()` method. @@ -139,7 +139,7 @@ class Restaurant(meta.Base): color=config.CUSTOMER_COLOR, fill_color=config.CUSTOMER_COLOR, fill_opacity=0.3, - tooltip=f'n_orders={n_orders}', + tooltip=f"n_orders={n_orders}", ) else: @@ -153,7 +153,7 @@ class Restaurant(meta.Base): color=config.RESTAURANT_COLOR, fill_color=config.RESTAURANT_COLOR, fill_opacity=0.3, - tooltip=f'{self.name} (#{self.id}) | n_orders={len(self.orders)}', + tooltip=f"{self.name} (#{self.id}) | n_orders={len(self.orders)}", ) return self.map diff --git a/src/velofy/db/utils/colors.py b/src/velofy/db/utils/colors.py index 0d90181..89ba6b3 100644 --- a/src/velofy/db/utils/colors.py +++ b/src/velofy/db/utils/colors.py @@ -49,7 +49,7 @@ def make_random_cmap( ] return colors.LinearSegmentedColormap.from_list( - 'random_color_map', + "random_color_map", rgb_colors, N=n_colors, ) @@ -69,4 +69,4 @@ def rgb_to_hex(*args: float) -> str: # pragma: no cover int(255 * args[1]), int(255 * args[2]), ) - return f'#{red:02x}{green:02x}{blue:02x}' + return f"#{red:02x}{green:02x}{blue:02x}" diff --git a/src/velofy/db/utils/locations.py b/src/velofy/db/utils/locations.py index 4a04492..3bd57c7 100644 --- a/src/velofy/db/utils/locations.py +++ b/src/velofy/db/utils/locations.py @@ -50,7 +50,7 @@ class Location: >>> Location(43.6532, -79.3832) """ - return f'' + return f"" @property def latitude(self) -> float: @@ -86,7 +86,7 @@ class Location: @property def zone(self) -> str: """The UTM zone of the location.""" - return f'{self._zone}{self._band}' + return f"{self._zone}{self._band}" @property def zone_details(self) -> Tuple[int, str]: @@ -99,7 +99,7 @@ class Location: return NotImplemented if self.zone != other.zone: - raise ValueError('locations must be in the same zone, including the band') + raise ValueError("locations must be in the same zone, including the band") return (self.easting, self.northing) == (other.easting, other.northing) @@ -110,7 +110,7 @@ class Location: The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`. """ if self._normalized_easting is None: - raise RuntimeError('an origin to relate to must be set first') + raise RuntimeError("an origin to relate to must be set first") return self._normalized_easting @@ -121,7 +121,7 @@ class Location: The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`. """ if self._normalized_northing is None: - raise RuntimeError('an origin to relate to must be set first') + raise RuntimeError("an origin to relate to must be set first") return self._normalized_northing @@ -136,13 +136,13 @@ class Location: properties, the `other` origin may only be set once! """ if self._normalized_easting is not None: - raise RuntimeError('the `other` origin may only be set once') + raise RuntimeError("the `other` origin may only be set once") if not isinstance(other, Location): - raise TypeError('`other` is not a `Location` object') + raise TypeError("`other` is not a `Location` object") if self.zone != other.zone: - raise ValueError('`other` must be in the same zone, including the band') + raise ValueError("`other` must be in the same zone, including the band") self._normalized_easting = self.easting - other.easting self._normalized_northing = self.northing - other.northing diff --git a/src/velofy/forecasts/methods/arima.py b/src/velofy/forecasts/methods/arima.py index 48849e3..7aa88f6 100644 --- a/src/velofy/forecasts/methods/arima.py +++ b/src/velofy/forecasts/methods/arima.py @@ -36,18 +36,18 @@ def predict( from velofy import init_r # noqa:F401 # Re-seed R every time it is used to ensure reproducibility. - robjects.r('set.seed(42)') + robjects.r("set.seed(42)") if training_ts.isnull().any(): - raise ValueError('`training_ts` must not contain `NaN` values') + raise ValueError("`training_ts` must not contain `NaN` values") # Copy the data from Python to R. - robjects.globalenv['data'] = robjects.r['ts']( + robjects.globalenv["data"] = robjects.r["ts"]( pandas2ri.py2rpy(training_ts), frequency=frequency, ) - seasonal = 'TRUE' if bool(seasonal_fit) else 'FALSE' + seasonal = "TRUE" if bool(seasonal_fit) else "FALSE" n_steps_ahead = len(forecast_interval) # Make the predictions in R. @@ -68,10 +68,10 @@ def predict( return forecasts.round(5).rename( columns={ - 'Point Forecast': 'prediction', - 'Lo 80': 'low80', - 'Hi 80': 'high80', - 'Lo 95': 'low95', - 'Hi 95': 'high95', + "Point Forecast": "prediction", + "Lo 80": "low80", + "Hi 80": "high80", + "Lo 95": "low95", + "Hi 95": "high95", }, ) diff --git a/src/velofy/forecasts/methods/decomposition.py b/src/velofy/forecasts/methods/decomposition.py index ebcd5e3..dfa0fef 100644 --- a/src/velofy/forecasts/methods/decomposition.py +++ b/src/velofy/forecasts/methods/decomposition.py @@ -95,17 +95,17 @@ def stl( # noqa:C901 # Validate all arguments and set default values. if time_series.isnull().any(): - raise ValueError('`time_series` must not contain `NaN` values') + raise ValueError("`time_series` must not contain `NaN` values") if ns % 2 == 0 or ns < 7: - raise ValueError('`ns` must be odd and `>= 7`') + raise ValueError("`ns` must be odd and `>= 7`") default_nt = math.ceil((1.5 * frequency) / (1 - (1.5 / ns))) if nt is not None: if nt % 2 == 0 or nt < default_nt: raise ValueError( - '`nt` must be odd and `>= (1.5 * frequency) / [1 - (1.5 / ns)]`, ' - + 'which is {0}'.format(default_nt), + "`nt` must be odd and `>= (1.5 * frequency) / [1 - (1.5 / ns)]`, " + + "which is {0}".format(default_nt), ) else: nt = default_nt @@ -114,42 +114,42 @@ def stl( # noqa:C901 if nl is not None: if nl % 2 == 0 or nl < frequency: - raise ValueError('`nl` must be odd and `>= frequency`') + raise ValueError("`nl` must be odd and `>= frequency`") elif frequency % 2 == 0: nl = frequency + 1 else: # pragma: no cover => hard to construct edge case nl = frequency if ds not in {0, 1}: - raise ValueError('`ds` must be either `0` or `1`') + raise ValueError("`ds` must be either `0` or `1`") if dt not in {0, 1}: - raise ValueError('`dt` must be either `0` or `1`') + raise ValueError("`dt` must be either `0` or `1`") if dl not in {0, 1}: - raise ValueError('`dl` must be either `0` or `1`') + raise ValueError("`dl` must be either `0` or `1`") if js is not None: if js <= 0: - raise ValueError('`js` must be positive') + raise ValueError("`js` must be positive") else: js = math.ceil(ns / 10) if jt is not None: if jt <= 0: - raise ValueError('`jt` must be positive') + raise ValueError("`jt` must be positive") else: jt = math.ceil(nt / 10) if jl is not None: if jl <= 0: - raise ValueError('`jl` must be positive') + raise ValueError("`jl` must be positive") else: jl = math.ceil(nl / 10) if ni <= 0: - raise ValueError('`ni` must be positive') + raise ValueError("`ni` must be positive") if no < 0: - raise ValueError('`no` must be non-negative') + raise ValueError("`no` must be non-negative") elif no > 0: robust = True else: @@ -160,11 +160,11 @@ def stl( # noqa:C901 from velofy import init_r # noqa:F401 # Re-seed R every time it is used to ensure reproducibility. - robjects.r('set.seed(42)') + robjects.r("set.seed(42)") # Call the STL function in R. - ts = robjects.r['ts'](pandas2ri.py2rpy(time_series), frequency=frequency) - result = robjects.r['stl']( + ts = robjects.r["ts"](pandas2ri.py2rpy(time_series), frequency=frequency) + result = robjects.r["stl"]( ts, ns, ds, @@ -184,9 +184,9 @@ def stl( # noqa:C901 result = pandas2ri.rpy2py(result[0]) result = pd.DataFrame( data={ - 'seasonal': result[:, 0], - 'trend': result[:, 1], - 'residual': result[:, 2], + "seasonal": result[:, 0], + "trend": result[:, 1], + "residual": result[:, 2], }, index=time_series.index, ) diff --git a/src/velofy/forecasts/methods/ets.py b/src/velofy/forecasts/methods/ets.py index d8fd71d..39c443a 100644 --- a/src/velofy/forecasts/methods/ets.py +++ b/src/velofy/forecasts/methods/ets.py @@ -37,18 +37,18 @@ def predict( from velofy import init_r # noqa:F401 # Re-seed R every time it is used to ensure reproducibility. - robjects.r('set.seed(42)') + robjects.r("set.seed(42)") if training_ts.isnull().any(): - raise ValueError('`training_ts` must not contain `NaN` values') + raise ValueError("`training_ts` must not contain `NaN` values") # Copy the data from Python to R. - robjects.globalenv['data'] = robjects.r['ts']( + robjects.globalenv["data"] = robjects.r["ts"]( pandas2ri.py2rpy(training_ts), frequency=frequency, ) - model = 'ZZZ' if bool(seasonal_fit) else 'ZZN' + model = "ZZZ" if bool(seasonal_fit) else "ZZN" n_steps_ahead = len(forecast_interval) # Make the predictions in R. @@ -69,10 +69,10 @@ def predict( return forecasts.round(5).rename( columns={ - 'Point Forecast': 'prediction', - 'Lo 80': 'low80', - 'Hi 80': 'high80', - 'Lo 95': 'low95', - 'Hi 95': 'high95', + "Point Forecast": "prediction", + "Lo 80": "low80", + "Hi 80": "high80", + "Lo 95": "low95", + "Hi 95": "high95", }, ) diff --git a/src/velofy/forecasts/methods/extrapolate_season.py b/src/velofy/forecasts/methods/extrapolate_season.py index 8e8a600..a6ea8f6 100644 --- a/src/velofy/forecasts/methods/extrapolate_season.py +++ b/src/velofy/forecasts/methods/extrapolate_season.py @@ -37,7 +37,7 @@ def predict( could not be made for time steps in the `forecast_interval` """ if training_ts.isnull().any(): - raise ValueError('`training_ts` must not contain `NaN` values') + raise ValueError("`training_ts` must not contain `NaN` values") extrapolated_ts = pd.Series(index=forecast_interval, dtype=float) seasonal_lag = frequency * (training_ts.index[1] - training_ts.index[0]) @@ -61,15 +61,15 @@ def predict( # Sanity check. if extrapolated_ts.isnull().any(): # pragma: no cover - raise ValueError('missing predictions in the `forecast_interval`') + raise ValueError("missing predictions in the `forecast_interval`") return pd.DataFrame( data={ - 'prediction': extrapolated_ts.round(5), - 'low80': float('NaN'), - 'high80': float('NaN'), - 'low95': float('NaN'), - 'high95': float('NaN'), + "prediction": extrapolated_ts.round(5), + "low80": float("NaN"), + "high80": float("NaN"), + "low95": float("NaN"), + "high95": float("NaN"), }, index=forecast_interval, ) diff --git a/src/velofy/forecasts/models/base.py b/src/velofy/forecasts/models/base.py index 8eae03e..c1fc40a 100644 --- a/src/velofy/forecasts/models/base.py +++ b/src/velofy/forecasts/models/base.py @@ -118,5 +118,5 @@ class ForecastingModelABC(abc.ABC): # ..., however, we put in a loud error, just in case. raise RuntimeError( # pragma: no cover - '`Forecast` for `predict_at` was not returned by `*Model.predict()`', + "`Forecast` for `predict_at` was not returned by `*Model.predict()`", ) diff --git a/src/velofy/forecasts/models/tactical/horizontal.py b/src/velofy/forecasts/models/tactical/horizontal.py index a0708d3..51dab1f 100644 --- a/src/velofy/forecasts/models/tactical/horizontal.py +++ b/src/velofy/forecasts/models/tactical/horizontal.py @@ -19,7 +19,7 @@ from velofy.forecasts.models import base class HorizontalETSModel(base.ForecastingModelABC): """The ETS model applied on a horizontal time series.""" - name = 'hets' + name = "hets" def predict( self, @@ -51,7 +51,7 @@ class HorizontalETSModel(base.ForecastingModelABC): # Sanity check. if frequency != 7: # pragma: no cover - raise RuntimeError('`frequency` should be `7`') + raise RuntimeError("`frequency` should be `7`") # Make `predictions` with the seasonal ETS method ("ZZZ" model). predictions = methods.ets.predict( @@ -61,13 +61,13 @@ class HorizontalETSModel(base.ForecastingModelABC): seasonal_fit=True, # because there was no decomposition before ) - predictions.insert(loc=0, column='actual', value=actuals_ts) + predictions.insert(loc=0, column="actual", value=actuals_ts) # Sanity checks. if predictions.isnull().sum().any(): # pragma: no cover - raise RuntimeError('missing predictions in hets model') + raise RuntimeError("missing predictions in hets model") if predict_at not in predictions.index: # pragma: no cover - raise RuntimeError('missing prediction for `predict_at`') + raise RuntimeError("missing prediction for `predict_at`") return predictions @@ -75,7 +75,7 @@ class HorizontalETSModel(base.ForecastingModelABC): class HorizontalSMAModel(base.ForecastingModelABC): """A simple moving average model applied on a horizontal time series.""" - name = 'hsma' + name = "hsma" def predict( self, @@ -107,10 +107,10 @@ class HorizontalSMAModel(base.ForecastingModelABC): # Sanity checks. if frequency != 7: # pragma: no cover - raise RuntimeError('`frequency` should be `7`') + raise RuntimeError("`frequency` should be `7`") if len(actuals_ts) != 1: # pragma: no cover raise RuntimeError( - 'the hsma model can only predict one step into the future', + "the hsma model can only predict one step into the future", ) # The "prediction" is calculated as the `np.mean()`. @@ -118,23 +118,23 @@ class HorizontalSMAModel(base.ForecastingModelABC): # no adjustment regarding the weekly seasonality is needed. predictions = pd.DataFrame( data={ - 'actual': actuals_ts, - 'prediction': training_ts.values.mean(), - 'low80': float('NaN'), - 'high80': float('NaN'), - 'low95': float('NaN'), - 'high95': float('NaN'), + "actual": actuals_ts, + "prediction": training_ts.values.mean(), + "low80": float("NaN"), + "high80": float("NaN"), + "low95": float("NaN"), + "high95": float("NaN"), }, index=actuals_ts.index, ) # Sanity checks. if ( - predictions[['actual', 'prediction']].isnull().any().any() + predictions[["actual", "prediction"]].isnull().any().any() ): # pragma: no cover - raise RuntimeError('missing predictions in hsma model') + raise RuntimeError("missing predictions in hsma model") if predict_at not in predictions.index: # pragma: no cover - raise RuntimeError('missing prediction for `predict_at`') + raise RuntimeError("missing prediction for `predict_at`") return predictions diff --git a/src/velofy/forecasts/models/tactical/other.py b/src/velofy/forecasts/models/tactical/other.py index 086b976..04c63d6 100644 --- a/src/velofy/forecasts/models/tactical/other.py +++ b/src/velofy/forecasts/models/tactical/other.py @@ -19,7 +19,7 @@ class TrivialModel(base.ForecastingModelABC): "real-time" model here as all give the same prediction for all time steps. """ - name = 'trivial' + name = "trivial" def predict( self, @@ -52,29 +52,29 @@ class TrivialModel(base.ForecastingModelABC): # Sanity checks. if frequency != 7: # pragma: no cover - raise RuntimeError('`frequency` should be `7`') + raise RuntimeError("`frequency` should be `7`") if len(actuals_ts) != 1: # pragma: no cover raise RuntimeError( - 'the trivial model can only predict one step into the future', + "the trivial model can only predict one step into the future", ) # The "prediction" is simply `0.0`. predictions = pd.DataFrame( data={ - 'actual': actuals_ts, - 'prediction': 0.0, - 'low80': float('NaN'), - 'high80': float('NaN'), - 'low95': float('NaN'), - 'high95': float('NaN'), + "actual": actuals_ts, + "prediction": 0.0, + "low80": float("NaN"), + "high80": float("NaN"), + "low95": float("NaN"), + "high95": float("NaN"), }, index=actuals_ts.index, ) # Sanity checks. - if predictions['actual'].isnull().any(): # pragma: no cover - raise RuntimeError('missing actuals in trivial model') + if predictions["actual"].isnull().any(): # pragma: no cover + raise RuntimeError("missing actuals in trivial model") if predict_at not in predictions.index: # pragma: no cover - raise RuntimeError('missing prediction for `predict_at`') + raise RuntimeError("missing prediction for `predict_at`") return predictions diff --git a/src/velofy/forecasts/models/tactical/realtime.py b/src/velofy/forecasts/models/tactical/realtime.py index 4040f1e..bf17a31 100644 --- a/src/velofy/forecasts/models/tactical/realtime.py +++ b/src/velofy/forecasts/models/tactical/realtime.py @@ -21,7 +21,7 @@ from velofy.forecasts.models import base class RealtimeARIMAModel(base.ForecastingModelABC): """The ARIMA model applied on a real-time time series.""" - name = 'rtarima' + name = "rtarima" def predict( self, @@ -63,7 +63,7 @@ class RealtimeARIMAModel(base.ForecastingModelABC): # Make predictions for the seasonal component by linear extrapolation. seasonal_predictions = methods.extrapolate_season.predict( - training_ts=decomposed_training_ts['seasonal'], + training_ts=decomposed_training_ts["seasonal"], forecast_interval=pd.DatetimeIndex(actuals_ts.index), frequency=frequency, ) @@ -71,7 +71,7 @@ class RealtimeARIMAModel(base.ForecastingModelABC): # Make predictions with the ARIMA model on the seasonally adjusted time series. seasonally_adjusted_predictions = methods.arima.predict( training_ts=( - decomposed_training_ts['trend'] + decomposed_training_ts['residual'] + decomposed_training_ts["trend"] + decomposed_training_ts["residual"] ), forecast_interval=pd.DatetimeIndex(actuals_ts.index), # Because the seasonality was taken out before, @@ -86,26 +86,26 @@ class RealtimeARIMAModel(base.ForecastingModelABC): # the extrapolated seasonal component. predictions = pd.DataFrame( data={ - 'actual': actuals_ts, - 'prediction': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['prediction'] + "actual": actuals_ts, + "prediction": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["prediction"] ), - 'low80': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['low80'] + "low80": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["low80"] ), - 'high80': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['high80'] + "high80": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["high80"] ), - 'low95': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['low95'] + "low95": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["low95"] ), - 'high95': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['high95'] + "high95": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["high95"] ), }, index=actuals_ts.index, @@ -113,10 +113,10 @@ class RealtimeARIMAModel(base.ForecastingModelABC): # Sanity checks. if len(predictions) != 1: # pragma: no cover - raise RuntimeError('real-time models should predict exactly one time step') + raise RuntimeError("real-time models should predict exactly one time step") if predictions.isnull().sum().any(): # pragma: no cover - raise RuntimeError('missing predictions in rtarima model') + raise RuntimeError("missing predictions in rtarima model") if predict_at not in predictions.index: # pragma: no cover - raise RuntimeError('missing prediction for `predict_at`') + raise RuntimeError("missing prediction for `predict_at`") return predictions diff --git a/src/velofy/forecasts/models/tactical/vertical.py b/src/velofy/forecasts/models/tactical/vertical.py index 82530a5..ebbc521 100644 --- a/src/velofy/forecasts/models/tactical/vertical.py +++ b/src/velofy/forecasts/models/tactical/vertical.py @@ -21,7 +21,7 @@ from velofy.forecasts.models import base class VerticalARIMAModel(base.ForecastingModelABC): """The ARIMA model applied on a vertical time series.""" - name = 'varima' + name = "varima" def predict( self, @@ -63,7 +63,7 @@ class VerticalARIMAModel(base.ForecastingModelABC): # Make predictions for the seasonal component by linear extrapolation. seasonal_predictions = methods.extrapolate_season.predict( - training_ts=decomposed_training_ts['seasonal'], + training_ts=decomposed_training_ts["seasonal"], forecast_interval=pd.DatetimeIndex(actuals_ts.index), frequency=frequency, ) @@ -71,7 +71,7 @@ class VerticalARIMAModel(base.ForecastingModelABC): # Make predictions with the ARIMA model on the seasonally adjusted time series. seasonally_adjusted_predictions = methods.arima.predict( training_ts=( - decomposed_training_ts['trend'] + decomposed_training_ts['residual'] + decomposed_training_ts["trend"] + decomposed_training_ts["residual"] ), forecast_interval=pd.DatetimeIndex(actuals_ts.index), # Because the seasonality was taken out before, @@ -86,26 +86,26 @@ class VerticalARIMAModel(base.ForecastingModelABC): # the extrapolated seasonal component. predictions = pd.DataFrame( data={ - 'actual': actuals_ts, - 'prediction': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['prediction'] + "actual": actuals_ts, + "prediction": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["prediction"] ), - 'low80': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['low80'] + "low80": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["low80"] ), - 'high80': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['high80'] + "high80": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["high80"] ), - 'low95': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['low95'] + "low95": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["low95"] ), - 'high95': ( - seasonal_predictions['prediction'] - + seasonally_adjusted_predictions['high95'] + "high95": ( + seasonal_predictions["prediction"] + + seasonally_adjusted_predictions["high95"] ), }, index=actuals_ts.index, @@ -113,10 +113,10 @@ class VerticalARIMAModel(base.ForecastingModelABC): # Sanity checks. if len(predictions) <= 1: # pragma: no cover - raise RuntimeError('vertical models should predict several time steps') + raise RuntimeError("vertical models should predict several time steps") if predictions.isnull().sum().any(): # pragma: no cover - raise RuntimeError('missing predictions in varima model') + raise RuntimeError("missing predictions in varima model") if predict_at not in predictions.index: # pragma: no cover - raise RuntimeError('missing prediction for `predict_at`') + raise RuntimeError("missing prediction for `predict_at`") return predictions diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index dd78c1b..e5d928b 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -37,7 +37,7 @@ class OrderHistory: 60 * (config.SERVICE_END - config.SERVICE_START) / time_step ) if n_daily_time_steps != int(n_daily_time_steps): # pragma: no cover - raise RuntimeError('Internal error: configuration has invalid TIME_STEPS') + raise RuntimeError("Internal error: configuration has invalid TIME_STEPS") self._n_daily_time_steps = int(n_daily_time_steps) # The `_data` are populated by `.aggregate_orders()`. @@ -141,7 +141,7 @@ class OrderHistory: """, ), con=db.connection, - index_col=['pixel_id', 'start_at'], + index_col=["pixel_id", "start_at"], ) if data.empty: @@ -162,13 +162,13 @@ class OrderHistory: gen = ( (pixel_id, start_at) for pixel_id in sorted(data.index.levels[0]) - for start_at in pd.date_range(start, end, freq=f'{self._time_step}min') + for start_at in pd.date_range(start, end, freq=f"{self._time_step}min") if config.SERVICE_START <= start_at.hour < config.SERVICE_END ) # Re-index `data` filling in `0`s where there is no demand. index = pd.MultiIndex.from_tuples(gen) - index.names = ['pixel_id', 'start_at'] + index.names = ["pixel_id", "start_at"] return data.reindex(index, fill_value=0) @@ -189,13 +189,13 @@ class OrderHistory: try: intra_pixel = self.totals.loc[pixel_id] except KeyError: - raise LookupError('The `pixel_id` is not in the `grid`') from None + raise LookupError("The `pixel_id` is not in the `grid`") from None - first_order = intra_pixel[intra_pixel['n_orders'] > 0].index.min() + first_order = intra_pixel[intra_pixel["n_orders"] > 0].index.min() # Sanity check: without an `Order`, the `Pixel` should not exist. if first_order is pd.NaT: # pragma: no cover - raise RuntimeError('no orders in the pixel') + raise RuntimeError("no orders in the pixel") # Return a proper `datetime.datetime` object. return dt.datetime( @@ -223,13 +223,13 @@ class OrderHistory: try: intra_pixel = self.totals.loc[pixel_id] except KeyError: - raise LookupError('The `pixel_id` is not in the `grid`') from None + raise LookupError("The `pixel_id` is not in the `grid`") from None - last_order = intra_pixel[intra_pixel['n_orders'] > 0].index.max() + last_order = intra_pixel[intra_pixel["n_orders"] > 0].index.max() # Sanity check: without an `Order`, the `Pixel` should not exist. if last_order is pd.NaT: # pragma: no cover - raise RuntimeError('no orders in the pixel') + raise RuntimeError("no orders in the pixel") # Return a proper `datetime.datetime` object. return dt.datetime( @@ -270,10 +270,10 @@ class OrderHistory: try: intra_pixel = self.totals.loc[pixel_id] except KeyError: - raise LookupError('The `pixel_id` is not in the `grid`') from None + raise LookupError("The `pixel_id` is not in the `grid`") from None if predict_at >= config.CUTOFF_DAY: # pragma: no cover - raise RuntimeError('Internal error: cannot predict beyond the given data') + raise RuntimeError("Internal error: cannot predict beyond the given data") # The first and last training day are just before the `predict_at` day # and span exactly `train_horizon` weeks covering only the times of the @@ -301,14 +301,14 @@ class OrderHistory: # Take only the counts at the `predict_at` time. training_ts = intra_pixel.loc[ first_start_at : last_start_at : self._n_daily_time_steps, # type:ignore - 'n_orders', + "n_orders", ] if len(training_ts) != frequency * train_horizon: - raise RuntimeError('Not enough historic data for `predict_at`') + raise RuntimeError("Not enough historic data for `predict_at`") - actuals_ts = intra_pixel.loc[[predict_at], 'n_orders'] + actuals_ts = intra_pixel.loc[[predict_at], "n_orders"] if not len(actuals_ts): # pragma: no cover - raise LookupError('`predict_at` is not in the order history') + raise LookupError("`predict_at` is not in the order history") return training_ts, frequency, actuals_ts @@ -342,10 +342,10 @@ class OrderHistory: try: intra_pixel = self.totals.loc[pixel_id] except KeyError: - raise LookupError('The `pixel_id` is not in the `grid`') from None + raise LookupError("The `pixel_id` is not in the `grid`") from None if predict_day >= config.CUTOFF_DAY.date(): # pragma: no cover - raise RuntimeError('Internal error: cannot predict beyond the given data') + raise RuntimeError("Internal error: cannot predict beyond the given data") # The first and last training day are just before the `predict_day` # and span exactly `train_horizon` weeks covering all times of the day. @@ -372,10 +372,10 @@ class OrderHistory: # Take all the counts between `first_train_day` and `last_train_day`. training_ts = intra_pixel.loc[ first_start_at:last_start_at, # type:ignore - 'n_orders', + "n_orders", ] if len(training_ts) != frequency * train_horizon: - raise RuntimeError('Not enough historic data for `predict_day`') + raise RuntimeError("Not enough historic data for `predict_day`") first_prediction_at = dt.datetime( predict_day.year, @@ -394,10 +394,10 @@ class OrderHistory: actuals_ts = intra_pixel.loc[ first_prediction_at:last_prediction_at, # type:ignore - 'n_orders', + "n_orders", ] if not len(actuals_ts): # pragma: no cover - raise LookupError('`predict_day` is not in the order history') + raise LookupError("`predict_day` is not in the order history") return training_ts, frequency, actuals_ts @@ -431,10 +431,10 @@ class OrderHistory: try: intra_pixel = self.totals.loc[pixel_id] except KeyError: - raise LookupError('The `pixel_id` is not in the `grid`') from None + raise LookupError("The `pixel_id` is not in the `grid`") from None if predict_at >= config.CUTOFF_DAY: # pragma: no cover - raise RuntimeError('Internal error: cannot predict beyond the given data') + raise RuntimeError("Internal error: cannot predict beyond the given data") # The first and last training day are just before the `predict_at` day # and span exactly `train_horizon` weeks covering all times of the day, @@ -472,7 +472,7 @@ class OrderHistory: # including the ones on the `predict_at` day prior to `predict_at`. training_ts = intra_pixel.loc[ first_start_at:last_start_at, # type:ignore - 'n_orders', + "n_orders", ] n_time_steps_on_predict_day = ( ( @@ -489,11 +489,11 @@ class OrderHistory: // self._time_step ) if len(training_ts) != frequency * train_horizon + n_time_steps_on_predict_day: - raise RuntimeError('Not enough historic data for `predict_day`') + raise RuntimeError("Not enough historic data for `predict_day`") - actuals_ts = intra_pixel.loc[[predict_at], 'n_orders'] + actuals_ts = intra_pixel.loc[[predict_at], "n_orders"] if not len(actuals_ts): # pragma: no cover - raise LookupError('`predict_at` is not in the order history') + raise LookupError("`predict_at` is not in the order history") return training_ts, frequency, actuals_ts @@ -587,5 +587,5 @@ class OrderHistory: return models.TrivialModel(order_history=self) raise RuntimeError( - 'no rule for the given average daily demand and training horizon', + "no rule for the given average daily demand and training horizon", ) diff --git a/src/velofy/init_r.py b/src/velofy/init_r.py index 5ef24ba..f9c2571 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -20,8 +20,8 @@ rcallbacks.consolewrite_warnerror = lambda msg: None # pragma: no cover # For clarity and convenience, re-raise the error that results from missing R # dependencies with clearer instructions as to how to deal with it. try: - rpackages.importr('forecast') - rpackages.importr('zoo') + rpackages.importr("forecast") + rpackages.importr("zoo") except rpackages.PackageNotInstalledError: # pragma: no cover msg = 'See the "research/00_r_dependencies.ipynb" notebook!' diff --git a/tests/conftest.py b/tests/conftest.py index 2e7c583..276199a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -20,14 +20,14 @@ from velofy import db # The TESTING environment variable is set # in pyproject.toml in pytest's config section. -if not os.getenv('TESTING'): - raise RuntimeError('Tests must be executed with TESTING set in the environment') +if not os.getenv("TESTING"): + raise RuntimeError("Tests must be executed with TESTING set in the environment") if not config.TESTING: - raise RuntimeError('The testing configuration was not loaded') + raise RuntimeError("The testing configuration was not loaded") -@pytest.fixture(scope='session', params=['all_at_once', 'sequentially']) +@pytest.fixture(scope="session", params=["all_at_once", "sequentially"]) def db_connection(request): """Create all tables given the ORM models. @@ -53,13 +53,13 @@ def db_connection(request): db.engine = engine db.connection = connection - if request.param == 'all_at_once': + if request.param == "all_at_once": with connection.begin(): - connection.execute(sa.text(f'CREATE SCHEMA {config.CLEAN_SCHEMA};')) + connection.execute(sa.text(f"CREATE SCHEMA {config.CLEAN_SCHEMA};")) db.Base.metadata.create_all(connection) else: - cfg = migrations_config.Config('alembic.ini') - migrations_cmd.upgrade(cfg, 'head') + cfg = migrations_config.Config("alembic.ini") + migrations_cmd.upgrade(cfg, "head") try: yield connection @@ -70,13 +70,13 @@ def db_connection(request): connection.close() with engine.begin() as cleanup: - cleanup.execute(sa.text(f'DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;')) + cleanup.execute(sa.text(f"DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;")) - if request.param == 'sequentially': - tmp_alembic_version = f'{config.ALEMBIC_TABLE}_{config.CLEAN_SCHEMA}' + if request.param == "sequentially": + tmp_alembic_version = f"{config.ALEMBIC_TABLE}_{config.CLEAN_SCHEMA}" cleanup.execute( sa.text( - f'DROP TABLE {config.ALEMBIC_TABLE_SCHEMA}.{tmp_alembic_version};', # noqa:E501 + f"DROP TABLE {config.ALEMBIC_TABLE_SCHEMA}.{tmp_alembic_version};", # noqa:E501 ), ) diff --git a/tests/console/test_gridify.py b/tests/console/test_gridify.py index c5600cf..660edb1 100644 --- a/tests/console/test_gridify.py +++ b/tests/console/test_gridify.py @@ -44,7 +44,7 @@ def test_two_pixels_with_two_addresses( side_length = max(city.total_x // 2, city.total_y // 2) + 1 # Hack the configuration regarding the grids to be created. - monkeypatch.setattr(velofy.config, 'GRID_SIDE_LENGTHS', [side_length]) + monkeypatch.setattr(velofy.config, "GRID_SIDE_LENGTHS", [side_length]) result = cli.invoke(gridify.gridify) diff --git a/tests/console/test_main.py b/tests/console/test_main.py index bef0056..2dae56a 100644 --- a/tests/console/test_main.py +++ b/tests/console/test_main.py @@ -25,35 +25,35 @@ class TestShowVersion: def test_no_version(self, capsys, ctx): """Test the early exit branch without any output.""" - main.show_version(ctx, _param='discarded', value=False) + main.show_version(ctx, _param="discarded", value=False) captured = capsys.readouterr() - assert captured.out == '' + assert captured.out == "" def test_final_version(self, capsys, ctx, monkeypatch): """For final versions, NO "development" warning is emitted.""" - version = '1.2.3' - monkeypatch.setattr(main.velofy, '__version__', version) + version = "1.2.3" + monkeypatch.setattr(main.velofy, "__version__", version) with pytest.raises(click.exceptions.Exit): - main.show_version(ctx, _param='discarded', value=True) + main.show_version(ctx, _param="discarded", value=True) captured = capsys.readouterr() - assert captured.out.endswith(f', version {version}\n') + assert captured.out.endswith(f", version {version}\n") def test_develop_version(self, capsys, ctx, monkeypatch): """For develop versions, a warning thereof is emitted.""" - version = '1.2.3.dev0' - monkeypatch.setattr(main.velofy, '__version__', version) + version = "1.2.3.dev0" + monkeypatch.setattr(main.velofy, "__version__", version) with pytest.raises(click.exceptions.Exit): - main.show_version(ctx, _param='discarded', value=True) + main.show_version(ctx, _param="discarded", value=True) captured = capsys.readouterr() - assert captured.out.strip().endswith(f', version {version} (development)') + assert captured.out.strip().endswith(f", version {version} (development)") class TestCLIWithoutCommand: @@ -72,28 +72,28 @@ class TestCLIWithoutCommand: # The following test cases validate the --version / -V option. - version_options = ('--version', '-V') + version_options = ("--version", "-V") @pytest.mark.no_cover - @pytest.mark.parametrize('option', version_options) + @pytest.mark.parametrize("option", version_options) def test_final_version(self, cli, monkeypatch, option): """For final versions, NO "development" warning is emitted.""" - version = '1.2.3' - monkeypatch.setattr(main.velofy, '__version__', version) + version = "1.2.3" + monkeypatch.setattr(main.velofy, "__version__", version) result = cli.invoke(main.entry_point, option) assert result.exit_code == 0 - assert result.output.strip().endswith(f', version {version}') + assert result.output.strip().endswith(f", version {version}") @pytest.mark.no_cover - @pytest.mark.parametrize('option', version_options) + @pytest.mark.parametrize("option", version_options) def test_develop_version(self, cli, monkeypatch, option): """For develop versions, a warning thereof is emitted.""" - version = '1.2.3.dev0' - monkeypatch.setattr(main.velofy, '__version__', version) + version = "1.2.3.dev0" + monkeypatch.setattr(main.velofy, "__version__", version) result = cli.invoke(main.entry_point, option) assert result.exit_code == 0 - assert result.output.strip().endswith(f', version {version} (development)') + assert result.output.strip().endswith(f", version {version} (development)") diff --git a/tests/db/fake_data/factories/addresses.py b/tests/db/fake_data/factories/addresses.py index 8615489..b519e46 100644 --- a/tests/db/fake_data/factories/addresses.py +++ b/tests/db/fake_data/factories/addresses.py @@ -15,7 +15,7 @@ class AddressFactory(alchemy.SQLAlchemyModelFactory): class Meta: model = db.Address - sqlalchemy_get_or_create = ('id',) + sqlalchemy_get_or_create = ("id",) id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) @@ -28,13 +28,13 @@ class AddressFactory(alchemy.SQLAlchemyModelFactory): # Mimic a Google Maps Place ID with just random characters. place_id = factory.LazyFunction( - lambda: ''.join(random.choice(string.ascii_lowercase) for _ in range(20)), + lambda: "".join(random.choice(string.ascii_lowercase) for _ in range(20)), ) # Place the addresses somewhere in downtown Paris. - latitude = factory.Faker('coordinate', center=48.855, radius=0.01) - longitude = factory.Faker('coordinate', center=2.34, radius=0.03) + latitude = factory.Faker("coordinate", center=48.855, radius=0.01) + longitude = factory.Faker("coordinate", center=2.34, radius=0.03) # city -> set by the `make_address` fixture as there is only one `city` - city_name = 'Paris' + city_name = "Paris" zip_code = factory.LazyFunction(lambda: random.randint(75001, 75020)) - street = factory.Faker('street_address', locale='fr_FR') + street = factory.Faker("street_address", locale="fr_FR") diff --git a/tests/db/fake_data/factories/couriers.py b/tests/db/fake_data/factories/couriers.py index c6bf8bd..c8c14f7 100644 --- a/tests/db/fake_data/factories/couriers.py +++ b/tests/db/fake_data/factories/couriers.py @@ -12,11 +12,11 @@ class CourierFactory(alchemy.SQLAlchemyModelFactory): class Meta: model = db.Courier - sqlalchemy_get_or_create = ('id',) + sqlalchemy_get_or_create = ("id",) id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) - vehicle = 'bicycle' + vehicle = "bicycle" historic_speed = 7.89 capacity = 100 pay_per_hour = 750 diff --git a/tests/db/fake_data/factories/customers.py b/tests/db/fake_data/factories/customers.py index accd5de..aee5eb8 100644 --- a/tests/db/fake_data/factories/customers.py +++ b/tests/db/fake_data/factories/customers.py @@ -11,6 +11,6 @@ class CustomerFactory(alchemy.SQLAlchemyModelFactory): class Meta: model = db.Customer - sqlalchemy_get_or_create = ('id',) + sqlalchemy_get_or_create = ("id",) id = factory.Sequence(lambda num: num) diff --git a/tests/db/fake_data/factories/orders/ad_hoc.py b/tests/db/fake_data/factories/orders/ad_hoc.py index 3154b8c..2ab9776 100644 --- a/tests/db/fake_data/factories/orders/ad_hoc.py +++ b/tests/db/fake_data/factories/orders/ad_hoc.py @@ -26,7 +26,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): class Meta: model = db.Order - sqlalchemy_get_or_create = ('id',) + sqlalchemy_get_or_create = ("id",) class Params: """Define flags that overwrite some attributes. diff --git a/tests/db/fake_data/factories/orders/replayed.py b/tests/db/fake_data/factories/orders/replayed.py index 326df02..090ff4f 100644 --- a/tests/db/fake_data/factories/orders/replayed.py +++ b/tests/db/fake_data/factories/orders/replayed.py @@ -17,7 +17,7 @@ class ReplayedOrderFactory(alchemy.SQLAlchemyModelFactory): class Meta: model = db.ReplayedOrder - sqlalchemy_get_or_create = ('simulation_id', 'order_id') + sqlalchemy_get_or_create = ("simulation_id", "order_id") # Generic columns # simulation -> set by the `make_replay_order` fixture for better control diff --git a/tests/db/fake_data/factories/restaurants.py b/tests/db/fake_data/factories/restaurants.py index 5d4b81f..c000a6f 100644 --- a/tests/db/fake_data/factories/restaurants.py +++ b/tests/db/fake_data/factories/restaurants.py @@ -16,7 +16,7 @@ class RestaurantFactory(alchemy.SQLAlchemyModelFactory): class Meta: model = db.Restaurant - sqlalchemy_get_or_create = ('id',) + sqlalchemy_get_or_create = ("id",) id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) diff --git a/tests/db/fake_data/fixture_makers.py b/tests/db/fake_data/fixture_makers.py index ffe6a3b..d2807b2 100644 --- a/tests/db/fake_data/fixture_makers.py +++ b/tests/db/fake_data/fixture_makers.py @@ -130,7 +130,7 @@ def make_replay_order(make_order, simulation): """ if scheduled: if order and order.ad_hoc is False: - raise RuntimeError('`order` must be scheduled') + raise RuntimeError("`order` must be scheduled") elif order is None: order = make_order(scheduled=True) elif order is None: diff --git a/tests/db/fake_data/static_fixtures.py b/tests/db/fake_data/static_fixtures.py index aa9e606..3923496 100644 --- a/tests/db/fake_data/static_fixtures.py +++ b/tests/db/fake_data/static_fixtures.py @@ -9,16 +9,16 @@ from velofy import db def city_data(): """The data for the one and only `City` object as a `dict`.""" return { - 'id': 1, - 'name': 'Paris', - 'kml': " ...", - 'center_latitude': 48.856614, - 'center_longitude': 2.3522219, - 'northeast_latitude': 48.9021449, - 'northeast_longitude': 2.4699208, - 'southwest_latitude': 48.815573, - 'southwest_longitude': 2.225193, - 'initial_zoom': 12, + "id": 1, + "name": "Paris", + "kml": " ...", + "center_latitude": 48.856614, + "center_longitude": 2.3522219, + "northeast_latitude": 48.9021449, + "northeast_longitude": 2.4699208, + "southwest_latitude": 48.815573, + "southwest_longitude": 2.225193, + "initial_zoom": 12, } @@ -86,10 +86,10 @@ def pixel(grid): def simulation_data(city): """The data for the one and only `ReplaySimulation` object as a `dict`.""" return { - 'id': 1, - 'city': city, - 'strategy': 'best_possible_routing', - 'run': 0, + "id": 1, + "city": city, + "strategy": "best_possible_routing", + "run": 0, } diff --git a/tests/db/replay/test_orders.py b/tests/db/replay/test_orders.py index c89ac5a..412416a 100644 --- a/tests/db/replay/test_orders.py +++ b/tests/db/replay/test_orders.py @@ -21,7 +21,7 @@ class TestSpecialMethods: """`ReplayedOrder` has a non-literal text representation.""" result = repr(replayed_order) - assert result == f'' + assert result == f"" @pytest.mark.db @@ -50,7 +50,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_replayed_orders_to_replay_simulations', + match="fk_replayed_orders_to_replay_simulations", ): db_session.execute(stmt) @@ -62,7 +62,7 @@ class TestConstraints: # Must delete without ORM as otherwise an UPDATE statement is emitted. stmt = sqla.delete(db.Order).where(db.Order.id == replayed_order.actual.id) - with pytest.raises(sa_exc.IntegrityError, match='fk_replayed_orders_to_orders'): + with pytest.raises(sa_exc.IntegrityError, match="fk_replayed_orders_to_orders"): db_session.execute(stmt) def test_delete_a_referenced_courier( @@ -84,7 +84,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_replayed_orders_to_couriers', + match="fk_replayed_orders_to_couriers", ): db_session.execute(stmt) @@ -98,7 +98,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='either_ad_hoc_or_scheduled_order', + match="either_ad_hoc_or_scheduled_order", ): db_session.commit() @@ -118,7 +118,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='either_ad_hoc_or_scheduled_order', + match="either_ad_hoc_or_scheduled_order", ): db_session.commit() @@ -132,7 +132,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ad_hoc_orders_within_business_hours', + match="ad_hoc_orders_within_business_hours", ): db_session.commit() @@ -146,7 +146,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ad_hoc_orders_within_business_hours', + match="ad_hoc_orders_within_business_hours", ): db_session.commit() @@ -165,7 +165,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_within_business_hours', + match="scheduled_orders_within_business_hours", ): db_session.commit() @@ -184,7 +184,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_within_business_hours', + match="scheduled_orders_within_business_hours", ): db_session.commit() @@ -224,11 +224,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_within_business_hours', + match="scheduled_orders_within_business_hours", ): db_session.commit() - @pytest.mark.parametrize('minute', [min_ for min_ in range(60) if min_ % 15 != 0]) + @pytest.mark.parametrize("minute", [min_ for min_ in range(60) if min_ % 15 != 0]) def test_scheduled_order_at_non_quarter_of_an_hour( self, db_session, @@ -253,11 +253,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_must_be_at_quart', # constraint name too long + match="scheduled_orders_must_be_at_quart", # constraint name too long ): db_session.commit() - @pytest.mark.parametrize('second', list(range(1, 60))) + @pytest.mark.parametrize("second", list(range(1, 60))) def test_scheduled_order_at_non_quarter_of_an_hour_by_seconds( self, db_session, @@ -283,7 +283,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_must_be_at_quart', # constraint name too long + match="scheduled_orders_must_be_at_quart", # constraint name too long ): db_session.commit() @@ -315,25 +315,25 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_not_within_30_minutes', + match="scheduled_orders_not_within_30_minutes", ): db_session.commit() @pytest.mark.parametrize( - 'column', + "column", [ - 'restaurant_notified_at', - 'restaurant_confirmed_at', - 'restaurant_ready_at', - 'dispatch_at', - 'courier', # not `.courier_id` - 'courier_notified_at', - 'courier_accepted_at', - 'reached_pickup_at', - 'pickup_at', - 'left_pickup_at', - 'reached_delivery_at', - 'delivery_at', + "restaurant_notified_at", + "restaurant_confirmed_at", + "restaurant_ready_at", + "dispatch_at", + "courier", # not `.courier_id` + "courier_notified_at", + "courier_accepted_at", + "reached_pickup_at", + "pickup_at", + "left_pickup_at", + "reached_delivery_at", + "delivery_at", ], ) def test_not_fully_simulated_order(self, db_session, replayed_order, column): @@ -346,21 +346,21 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='either_cancelled_o', # constraint name too long + match="either_cancelled_o", # constraint name too long ): db_session.commit() @pytest.mark.parametrize( - 'column', + "column", [ - 'restaurant_notified_at', - 'restaurant_confirmed_at', - 'restaurant_ready_at', - 'dispatch_at', - 'courier_id', - 'courier_notified_at', - 'courier_accepted_at', - 'reached_pickup_at', + "restaurant_notified_at", + "restaurant_confirmed_at", + "restaurant_ready_at", + "dispatch_at", + "courier_id", + "courier_notified_at", + "courier_accepted_at", + "reached_pickup_at", ], ) def test_simulated_cancellation(self, db_session, replayed_order, column): @@ -381,8 +381,8 @@ class TestConstraints: db_session.commit() @pytest.mark.parametrize( - 'column', - ['pickup_at', 'left_pickup_at', 'reached_delivery_at', 'delivery_at'], + "column", + ["pickup_at", "left_pickup_at", "reached_delivery_at", "delivery_at"], ) def test_no_simulated_cancellation_after_pickup( self, @@ -398,10 +398,10 @@ class TestConstraints: # Set all timestamps after `.reached_pickup_at` to NULL # except the one under test. for unset_column in ( - 'pickup_at', - 'left_pickup_at', - 'reached_delivery_at', - 'delivery_at', + "pickup_at", + "left_pickup_at", + "reached_delivery_at", + "delivery_at", ): if unset_column != column: setattr(replayed_order, unset_column, None) @@ -410,11 +410,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='cancellations_may_only_occur_befo', # constraint name too long + match="cancellations_may_only_occur_befo", # constraint name too long ): db_session.commit() - @pytest.mark.parametrize('duration', [-1, 3601]) + @pytest.mark.parametrize("duration", [-1, 3601]) def test_estimated_prep_duration_out_of_range( self, db_session, @@ -427,11 +427,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='between_0', # constraint name too long + match="between_0", # constraint name too long ): db_session.commit() - @pytest.mark.parametrize('duration', [1, 59, 119, 3599]) + @pytest.mark.parametrize("duration", [1, 59, 119, 3599]) def test_estimated_prep_duration_not_whole_minute( self, db_session, @@ -444,11 +444,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='must_be_w', # constraint name too long + match="must_be_w", # constraint name too long ): db_session.commit() - @pytest.mark.parametrize('utilization', [-1, 101]) + @pytest.mark.parametrize("utilization", [-1, 101]) def test_utilization_out_of_range(self, db_session, replayed_order, utilization): """Insert an instance with invalid data.""" replayed_order.utilization = utilization @@ -456,12 +456,12 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='between_0_and_100', + match="between_0_and_100", ): db_session.commit() - @pytest.mark.parametrize('column', ['restaurant_notified_at', 'dispatch_at']) - @pytest.mark.parametrize('hour', [0, 10]) + @pytest.mark.parametrize("column", ["restaurant_notified_at", "dispatch_at"]) + @pytest.mark.parametrize("hour", [0, 10]) def test_order_dispatched_in_non_business_hour( self, db_session, @@ -480,60 +480,60 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='business_hours', + match="business_hours", ): db_session.commit() @pytest.mark.parametrize( - 'comparison', + "comparison", [ - 'placed_at < restaurant_notified_at', - 'placed_at < restaurant_confirmed_at', - 'placed_at < restaurant_ready_at', - 'placed_at < dispatch_at', - 'placed_at < first_estimated_delivery_at', - 'placed_at < courier_notified_at', - 'placed_at < courier_accepted_at', - 'placed_at < reached_pickup_at', - 'placed_at < pickup_at', - 'placed_at < left_pickup_at', - 'placed_at < reached_delivery_at', - 'placed_at < delivery_at', - 'restaurant_notified_at < restaurant_confirmed_at', - 'restaurant_notified_at < restaurant_ready_at', - 'restaurant_notified_at < pickup_at', - 'restaurant_confirmed_at < restaurant_ready_at', - 'restaurant_confirmed_at < pickup_at', - 'restaurant_ready_at < pickup_at', - 'dispatch_at < first_estimated_delivery_at', - 'dispatch_at < courier_notified_at', - 'dispatch_at < courier_accepted_at', - 'dispatch_at < reached_pickup_at', - 'dispatch_at < pickup_at', - 'dispatch_at < left_pickup_at', - 'dispatch_at < reached_delivery_at', - 'dispatch_at < delivery_at', - 'courier_notified_at < courier_accepted_at', - 'courier_notified_at < reached_pickup_at', - 'courier_notified_at < pickup_at', - 'courier_notified_at < left_pickup_at', - 'courier_notified_at < reached_delivery_at', - 'courier_notified_at < delivery_at', - 'courier_accepted_at < reached_pickup_at', - 'courier_accepted_at < pickup_at', - 'courier_accepted_at < left_pickup_at', - 'courier_accepted_at < reached_delivery_at', - 'courier_accepted_at < delivery_at', - 'reached_pickup_at < pickup_at', - 'reached_pickup_at < left_pickup_at', - 'reached_pickup_at < reached_delivery_at', - 'reached_pickup_at < delivery_at', - 'pickup_at < left_pickup_at', - 'pickup_at < reached_delivery_at', - 'pickup_at < delivery_at', - 'left_pickup_at < reached_delivery_at', - 'left_pickup_at < delivery_at', - 'reached_delivery_at < delivery_at', + "placed_at < restaurant_notified_at", + "placed_at < restaurant_confirmed_at", + "placed_at < restaurant_ready_at", + "placed_at < dispatch_at", + "placed_at < first_estimated_delivery_at", + "placed_at < courier_notified_at", + "placed_at < courier_accepted_at", + "placed_at < reached_pickup_at", + "placed_at < pickup_at", + "placed_at < left_pickup_at", + "placed_at < reached_delivery_at", + "placed_at < delivery_at", + "restaurant_notified_at < restaurant_confirmed_at", + "restaurant_notified_at < restaurant_ready_at", + "restaurant_notified_at < pickup_at", + "restaurant_confirmed_at < restaurant_ready_at", + "restaurant_confirmed_at < pickup_at", + "restaurant_ready_at < pickup_at", + "dispatch_at < first_estimated_delivery_at", + "dispatch_at < courier_notified_at", + "dispatch_at < courier_accepted_at", + "dispatch_at < reached_pickup_at", + "dispatch_at < pickup_at", + "dispatch_at < left_pickup_at", + "dispatch_at < reached_delivery_at", + "dispatch_at < delivery_at", + "courier_notified_at < courier_accepted_at", + "courier_notified_at < reached_pickup_at", + "courier_notified_at < pickup_at", + "courier_notified_at < left_pickup_at", + "courier_notified_at < reached_delivery_at", + "courier_notified_at < delivery_at", + "courier_accepted_at < reached_pickup_at", + "courier_accepted_at < pickup_at", + "courier_accepted_at < left_pickup_at", + "courier_accepted_at < reached_delivery_at", + "courier_accepted_at < delivery_at", + "reached_pickup_at < pickup_at", + "reached_pickup_at < left_pickup_at", + "reached_pickup_at < reached_delivery_at", + "reached_pickup_at < delivery_at", + "pickup_at < left_pickup_at", + "pickup_at < reached_delivery_at", + "pickup_at < delivery_at", + "left_pickup_at < reached_delivery_at", + "left_pickup_at < delivery_at", + "reached_delivery_at < delivery_at", ], ) def test_timestamps_unordered( @@ -547,7 +547,7 @@ class TestConstraints: There are two special cases for this test case below, where other attributes on `replayed_order` must be unset. """ - smaller, bigger = comparison.split(' < ') + smaller, bigger = comparison.split(" < ") assert smaller is not None @@ -556,7 +556,7 @@ class TestConstraints: db_session.add(replayed_order) - with pytest.raises(sa_exc.IntegrityError, match='ordered_timestamps'): + with pytest.raises(sa_exc.IntegrityError, match="ordered_timestamps"): db_session.commit() def test_timestamps_unordered_scheduled(self, db_session, make_replay_order): @@ -571,20 +571,20 @@ class TestConstraints: self.test_timestamps_unordered( db_session, replayed_pre_order, - 'placed_at < scheduled_delivery_at', + "placed_at < scheduled_delivery_at", ) @pytest.mark.parametrize( - 'comparison', + "comparison", [ - 'placed_at < cancelled_at', - 'restaurant_notified_at < cancelled_at', - 'restaurant_confirmed_at < cancelled_at', - 'restaurant_ready_at < cancelled_at', - 'dispatch_at < cancelled_at', - 'courier_notified_at < cancelled_at', - 'courier_accepted_at < cancelled_at', - 'reached_pickup_at < cancelled_at', + "placed_at < cancelled_at", + "restaurant_notified_at < cancelled_at", + "restaurant_confirmed_at < cancelled_at", + "restaurant_ready_at < cancelled_at", + "dispatch_at < cancelled_at", + "courier_notified_at < cancelled_at", + "courier_accepted_at < cancelled_at", + "reached_pickup_at < cancelled_at", ], ) def test_timestamps_unordered_cancelled( diff --git a/tests/db/replay/test_simulations.py b/tests/db/replay/test_simulations.py index 5d2ce08..ee97549 100644 --- a/tests/db/replay/test_simulations.py +++ b/tests/db/replay/test_simulations.py @@ -12,6 +12,6 @@ class TestSpecialMethods: """`ReplaySimulation` has a non-literal text representation.""" result = repr(simulation) - assert result.startswith('' + assert result == f"" @pytest.mark.db @@ -47,7 +47,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_to_addresses_via_primary_id', + match="fk_addresses_to_addresses_via_primary_id", ): db_session.commit() @@ -61,11 +61,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_to_cities_via_city_id', + match="fk_addresses_to_cities_via_city_id", ): db_session.execute(stmt) - @pytest.mark.parametrize('latitude', [-91, 91]) + @pytest.mark.parametrize("latitude", [-91, 91]) def test_invalid_latitude(self, db_session, address, latitude): """Insert an instance with invalid data.""" address.latitude = latitude @@ -73,11 +73,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='latitude_between_90_degrees', + match="latitude_between_90_degrees", ): db_session.commit() - @pytest.mark.parametrize('longitude', [-181, 181]) + @pytest.mark.parametrize("longitude", [-181, 181]) def test_invalid_longitude(self, db_session, address, longitude): """Insert an instance with invalid data.""" address.longitude = longitude @@ -85,26 +85,26 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='longitude_between_180_degrees', + match="longitude_between_180_degrees", ): db_session.commit() - @pytest.mark.parametrize('zip_code', [-1, 0, 9999, 100000]) + @pytest.mark.parametrize("zip_code", [-1, 0, 9999, 100000]) def test_invalid_zip_code(self, db_session, address, zip_code): """Insert an instance with invalid data.""" address.zip_code = zip_code db_session.add(address) - with pytest.raises(sa_exc.IntegrityError, match='valid_zip_code'): + with pytest.raises(sa_exc.IntegrityError, match="valid_zip_code"): db_session.commit() - @pytest.mark.parametrize('floor', [-1, 41]) + @pytest.mark.parametrize("floor", [-1, 41]) def test_invalid_floor(self, db_session, address, floor): """Insert an instance with invalid data.""" address.floor = floor db_session.add(address) - with pytest.raises(sa_exc.IntegrityError, match='realistic_floor'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_floor"): db_session.commit() diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index 8786f2d..42cb93d 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -77,7 +77,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_addresses_to_addresses_via_first_address', # shortened + match="fk_addresses_addresses_to_addresses_via_first_address", # shortened ): db_session.execute(stmt) @@ -91,7 +91,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_addresses_to_addresses_via_second_address', # shortened + match="fk_addresses_addresses_to_addresses_via_second_address", # shortened ): db_session.execute(stmt) @@ -112,7 +112,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_addresses_to_addresses_via_first_address', # shortened + match="fk_addresses_addresses_to_addresses_via_first_address", # shortened ): db_session.execute(stmt) @@ -130,7 +130,7 @@ class TestConstraints: air_distance=path.air_distance, ) - with pytest.raises(sa_exc.IntegrityError, match='duplicate key value'): + with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"): db_session.execute(stmt) def test_symmetric_addresses(self, db_session, path): @@ -147,7 +147,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ck_addresses_addresses_on_distances_are_symmetric_for_bicycles', + match="ck_addresses_addresses_on_distances_are_symmetric_for_bicycles", ): db_session.commit() @@ -156,7 +156,7 @@ class TestConstraints: path.air_distance = -1 db_session.add(path) - with pytest.raises(sa_exc.IntegrityError, match='realistic_air_distance'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_air_distance"): db_session.commit() def test_air_distance_too_large(self, db_session, path): @@ -165,7 +165,7 @@ class TestConstraints: path.bicycle_distance = 21_000 db_session.add(path) - with pytest.raises(sa_exc.IntegrityError, match='realistic_air_distance'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_air_distance"): db_session.commit() def test_bicycle_distance_too_large(self, db_session, path): @@ -173,7 +173,7 @@ class TestConstraints: path.bicycle_distance = 25_000 db_session.add(path) - with pytest.raises(sa_exc.IntegrityError, match='realistic_bicycle_distance'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_bicycle_distance"): db_session.commit() def test_air_distance_shorter_than_bicycle_distance(self, db_session, path): @@ -181,10 +181,10 @@ class TestConstraints: path.bicycle_distance = round(0.75 * path.air_distance) db_session.add(path) - with pytest.raises(sa_exc.IntegrityError, match='air_distance_is_shortest'): + with pytest.raises(sa_exc.IntegrityError, match="air_distance_is_shortest"): db_session.commit() - @pytest.mark.parametrize('duration', [-1, 3601]) + @pytest.mark.parametrize("duration", [-1, 3601]) def test_unrealistic_bicycle_travel_time(self, db_session, path, duration): """Insert an instance with invalid data.""" path.bicycle_duration = duration @@ -192,7 +192,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='realistic_bicycle_travel_time', + match="realistic_bicycle_travel_time", ): db_session.commit() @@ -214,7 +214,7 @@ class TestFromAddresses: """ db_session.add(address) - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_make_path_instance( self, db_session, @@ -228,7 +228,7 @@ class TestFromAddresses: assert db_session.query(db.Path).count() == 1 - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_make_the_same_path_instance_twice( self, db_session, @@ -246,14 +246,14 @@ class TestFromAddresses: assert db_session.query(db.Path).count() == 1 - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_structure_of_return_value(self, db_session, address, another_address): """Test instantiation of a new `Path` instance.""" results = db.Path.from_addresses(address, another_address) assert isinstance(results, list) - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_instances_must_have_air_distance( self, db_session, @@ -267,7 +267,7 @@ class TestFromAddresses: assert result.air_distance is not None - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_do_not_sync_instances_with_google_maps( self, db_session, @@ -282,7 +282,7 @@ class TestFromAddresses: assert result.bicycle_distance is None assert result.bicycle_duration is None - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_sync_instances_with_google_maps( self, db_session, @@ -296,7 +296,7 @@ class TestFromAddresses: self.bicycle_distance = 1.25 * self.air_distance self.bicycle_duration = 300 - monkeypatch.setattr(db.Path, 'sync_with_google_maps', sync) + monkeypatch.setattr(db.Path, "sync_with_google_maps", sync) paths = db.Path.from_addresses(address, another_address, google_maps=True) @@ -305,21 +305,21 @@ class TestFromAddresses: assert result.bicycle_distance is not None assert result.bicycle_duration is not None - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_one_path_for_two_addresses(self, db_session, address, another_address): """Test instantiation of a new `Path` instance.""" result = len(db.Path.from_addresses(address, another_address)) assert result == 1 - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_two_paths_for_three_addresses(self, db_session, make_address): """Test instantiation of a new `Path` instance.""" result = len(db.Path.from_addresses(*[make_address() for _ in range(3)])) assert result == 3 - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_six_paths_for_four_addresses(self, db_session, make_address): """Test instantiation of a new `Path` instance.""" result = len(db.Path.from_addresses(*[make_address() for _ in range(4)])) @@ -328,7 +328,7 @@ class TestFromAddresses: # Tests for the `Path.from_order()` convenience method. - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_make_path_instance_from_order( self, db_session, @@ -341,7 +341,7 @@ class TestFromAddresses: assert db_session.query(db.Path).count() == 1 - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_make_the_same_path_instance_from_order_twice( self, db_session, @@ -358,14 +358,14 @@ class TestFromAddresses: assert db_session.query(db.Path).count() == 1 - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_structure_of_return_value_from_order(self, db_session, order): """Test instantiation of a new `Path` instance.""" result = db.Path.from_order(order) assert isinstance(result, db.Path) - @pytest.mark.usefixtures('_prepare_db') + @pytest.mark.usefixtures("_prepare_db") def test_sync_instance_from_order_with_google_maps( self, db_session, @@ -378,7 +378,7 @@ class TestFromAddresses: self.bicycle_distance = 1.25 * self.air_distance self.bicycle_duration = 300 - monkeypatch.setattr(db.Path, 'sync_with_google_maps', sync) + monkeypatch.setattr(db.Path, "sync_with_google_maps", sync) result = db.Path.from_order(order, google_maps=True) @@ -395,251 +395,251 @@ class TestSyncWithGoogleMaps: """A typical (shortened) response by the Google Maps Directions API.""" return [ { - 'bounds': { - 'northeast': {'lat': 44.8554284, 'lng': -0.5652398}, - 'southwest': {'lat': 44.8342256, 'lng': -0.5708206}, + "bounds": { + "northeast": {"lat": 44.8554284, "lng": -0.5652398}, + "southwest": {"lat": 44.8342256, "lng": -0.5708206}, }, - 'copyrights': 'Map data ©2021', - 'legs': [ + "copyrights": "Map data ©2021", + "legs": [ { # We choose an artificially high distance of `9999` # so that the synced bicycle distance is longer than # the randomized air distance (i.e., fake data) for sure. - 'distance': {'text': '3.0 km', 'value': 9999}, - 'duration': {'text': '10 mins', 'value': 596}, - 'end_address': '13 Place Paul et Jean Paul Avisseau, ...', - 'end_location': {'lat': 44.85540839999999, 'lng': -0.5672105}, - 'start_address': '59 Rue Saint-François, 33000 Bordeaux, ...', - 'start_location': {'lat': 44.8342256, 'lng': -0.570372}, - 'steps': [ + "distance": {"text": "3.0 km", "value": 9999}, + "duration": {"text": "10 mins", "value": 596}, + "end_address": "13 Place Paul et Jean Paul Avisseau, ...", + "end_location": {"lat": 44.85540839999999, "lng": -0.5672105}, + "start_address": "59 Rue Saint-François, 33000 Bordeaux, ...", + "start_location": {"lat": 44.8342256, "lng": -0.570372}, + "steps": [ { - 'distance': {'text': '0.1 km', 'value': 138}, - 'duration': {'text': '1 min', 'value': 43}, - 'end_location': { - 'lat': 44.83434380000001, - 'lng': -0.5690105999999999, + "distance": {"text": "0.1 km", "value": 138}, + "duration": {"text": "1 min", "value": 43}, + "end_location": { + "lat": 44.83434380000001, + "lng": -0.5690105999999999, }, - 'html_instructions': 'Head east on ...', - 'polyline': {'points': '}tspGxknBKcDIkB'}, - 'start_location': {'lat': 44.8342256, 'lng': -0.57032}, - 'travel_mode': 'BICYCLING', + "html_instructions": "Head east on ...", + "polyline": {"points": "}tspGxknBKcDIkB"}, + "start_location": {"lat": 44.8342256, "lng": -0.57032}, + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.1 km', 'value': 115}, - 'duration': {'text': '1 min', 'value': 22}, - 'end_location': {'lat': 44.8353651, 'lng': -0.569199}, - 'html_instructions': 'Turn left onto ...', - 'maneuver': 'turn-left', - 'polyline': {'points': 'suspGhcnBc@JE@_@DiAHA?w@F'}, - 'start_location': { - 'lat': 44.83434380000001, - 'lng': -0.5690105999999999, + "distance": {"text": "0.1 km", "value": 115}, + "duration": {"text": "1 min", "value": 22}, + "end_location": {"lat": 44.8353651, "lng": -0.569199}, + "html_instructions": "Turn left onto ...", + "maneuver": "turn-left", + "polyline": {"points": "suspGhcnBc@JE@_@DiAHA?w@F"}, + "start_location": { + "lat": 44.83434380000001, + "lng": -0.5690105999999999, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.3 km', 'value': 268}, - 'duration': {'text': '1 min', 'value': 59}, - 'end_location': {'lat': 44.8362675, 'lng': -0.5660914}, - 'html_instructions': 'Turn right onto ...', - 'maneuver': 'turn-right', - 'polyline': { - 'points': 'a|spGndnBEYEQKi@Mi@Is@CYCOE]CQIq@ ...', + "distance": {"text": "0.3 km", "value": 268}, + "duration": {"text": "1 min", "value": 59}, + "end_location": {"lat": 44.8362675, "lng": -0.5660914}, + "html_instructions": "Turn right onto ...", + "maneuver": "turn-right", + "polyline": { + "points": "a|spGndnBEYEQKi@Mi@Is@CYCOE]CQIq@ ...", }, - 'start_location': {'lat': 44.8353651, 'lng': -0.56919}, - 'travel_mode': 'BICYCLING', + "start_location": {"lat": 44.8353651, "lng": -0.56919}, + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.1 km', 'value': 95}, - 'duration': {'text': '1 min', 'value': 29}, - 'end_location': {'lat': 44.8368458, 'lng': -0.5652398}, - 'html_instructions': 'Slight left onto ...', - 'maneuver': 'turn-slight-left', - 'polyline': { - 'points': 'uatpG`qmBg@aAGM?ACE[k@CICGACEGCCAAEAG?', + "distance": {"text": "0.1 km", "value": 95}, + "duration": {"text": "1 min", "value": 29}, + "end_location": {"lat": 44.8368458, "lng": -0.5652398}, + "html_instructions": "Slight left onto ...", + "maneuver": "turn-slight-left", + "polyline": { + "points": "uatpG`qmBg@aAGM?ACE[k@CICGACEGCCAAEAG?", }, - 'start_location': { - 'lat': 44.8362675, - 'lng': -0.5660914, + "start_location": { + "lat": 44.8362675, + "lng": -0.5660914, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '23 m', 'value': 23}, - 'duration': {'text': '1 min', 'value': 4}, - 'end_location': {'lat': 44.83697, 'lng': -0.5654425}, - 'html_instructions': 'Slight left to stay ...', - 'maneuver': 'turn-slight-left', - 'polyline': { - 'points': 'ietpGvkmBA@C?CBCBEHA@AB?B?B?B?@', + "distance": {"text": "23 m", "value": 23}, + "duration": {"text": "1 min", "value": 4}, + "end_location": {"lat": 44.83697, "lng": -0.5654425}, + "html_instructions": "Slight left to stay ...", + "maneuver": "turn-slight-left", + "polyline": { + "points": "ietpGvkmBA@C?CBCBEHA@AB?B?B?B?@", }, - 'start_location': { - 'lat': 44.8368458, - 'lng': -0.5652398, + "start_location": { + "lat": 44.8368458, + "lng": -0.5652398, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.2 km', 'value': 185}, - 'duration': {'text': '1 min', 'value': 23}, - 'end_location': {'lat': 44.8382126, 'lng': -0.5669969}, - 'html_instructions': 'Take the ramp to Le Lac ...', - 'polyline': { - 'points': 'aftpG~lmBY^[^sAdB]`@CDKLQRa@h@A@IZ', + "distance": {"text": "0.2 km", "value": 185}, + "duration": {"text": "1 min", "value": 23}, + "end_location": {"lat": 44.8382126, "lng": -0.5669969}, + "html_instructions": "Take the ramp to Le Lac ...", + "polyline": { + "points": "aftpG~lmBY^[^sAdB]`@CDKLQRa@h@A@IZ", }, - 'start_location': {'lat': 44.83697, 'lng': -0.5654425}, - 'travel_mode': 'BICYCLING', + "start_location": {"lat": 44.83697, "lng": -0.5654425}, + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.3 km', 'value': 253}, - 'duration': {'text': '1 min', 'value': 43}, - 'end_location': {'lat': 44.840163, 'lng': -0.5686525}, - 'html_instructions': 'Merge onto Quai Richelieu', - 'maneuver': 'merge', - 'polyline': { - 'points': 'ymtpGvvmBeAbAe@b@_@ZUN[To@f@e@^A?g ...', + "distance": {"text": "0.3 km", "value": 253}, + "duration": {"text": "1 min", "value": 43}, + "end_location": {"lat": 44.840163, "lng": -0.5686525}, + "html_instructions": "Merge onto Quai Richelieu", + "maneuver": "merge", + "polyline": { + "points": "ymtpGvvmBeAbAe@b@_@ZUN[To@f@e@^A?g ...", }, - 'start_location': { - 'lat': 44.8382126, - 'lng': -0.5669969, + "start_location": { + "lat": 44.8382126, + "lng": -0.5669969, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.1 km', 'value': 110}, - 'duration': {'text': '1 min', 'value': 21}, - 'end_location': {'lat': 44.841079, 'lng': -0.5691835}, - 'html_instructions': 'Continue onto Quai de la ...', - 'polyline': {'points': '_ztpG`anBUNQLULUJOHMFKDWN'}, - 'start_location': {'lat': 44.840163, 'lng': -0.56865}, - 'travel_mode': 'BICYCLING', + "distance": {"text": "0.1 km", "value": 110}, + "duration": {"text": "1 min", "value": 21}, + "end_location": {"lat": 44.841079, "lng": -0.5691835}, + "html_instructions": "Continue onto Quai de la ...", + "polyline": {"points": "_ztpG`anBUNQLULUJOHMFKDWN"}, + "start_location": {"lat": 44.840163, "lng": -0.56865}, + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.3 km', 'value': 262}, - 'duration': {'text': '1 min', 'value': 44}, - 'end_location': {'lat': 44.8433375, 'lng': -0.5701161}, - 'html_instructions': 'Continue onto Quai du ...', - 'polyline': { - 'points': 'w_upGjdnBeBl@sBn@gA^[JIBc@Nk@Nk@L', + "distance": {"text": "0.3 km", "value": 262}, + "duration": {"text": "1 min", "value": 44}, + "end_location": {"lat": 44.8433375, "lng": -0.5701161}, + "html_instructions": "Continue onto Quai du ...", + "polyline": { + "points": "w_upGjdnBeBl@sBn@gA^[JIBc@Nk@Nk@L", }, - 'start_location': {'lat': 44.841079, 'lng': -0.56915}, - 'travel_mode': 'BICYCLING', + "start_location": {"lat": 44.841079, "lng": -0.56915}, + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.6 km', 'value': 550}, - 'duration': {'text': '2 mins', 'value': 97}, - 'end_location': { - 'lat': 44.84822339999999, - 'lng': -0.5705307, + "distance": {"text": "0.6 km", "value": 550}, + "duration": {"text": "2 mins", "value": 97}, + "end_location": { + "lat": 44.84822339999999, + "lng": -0.5705307, }, - 'html_instructions': 'Continue onto Quai ...', - 'polyline': { - 'points': '{mupGfjnBYFI@IBaAPUD{AX}@NK@]Fe@H ...', + "html_instructions": "Continue onto Quai ...", + "polyline": { + "points": "{mupGfjnBYFI@IBaAPUD{AX}@NK@]Fe@H ...", }, - 'start_location': { - 'lat': 44.8433375, - 'lng': -0.5701161, + "start_location": { + "lat": 44.8433375, + "lng": -0.5701161, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.5 km', 'value': 508}, - 'duration': {'text': '1 min', 'value': 87}, - 'end_location': {'lat': 44.8523224, 'lng': -0.5678223}, - 'html_instructions': 'Continue onto ...', - 'polyline': { - 'points': 'klvpGxlnBWEUGWGSGMEOEOE[KMEQGIA] ...', + "distance": {"text": "0.5 km", "value": 508}, + "duration": {"text": "1 min", "value": 87}, + "end_location": {"lat": 44.8523224, "lng": -0.5678223}, + "html_instructions": "Continue onto ...", + "polyline": { + "points": "klvpGxlnBWEUGWGSGMEOEOE[KMEQGIA] ...", }, - 'start_location': { - 'lat': 44.84822339999999, - 'lng': -0.5705307, + "start_location": { + "lat": 44.84822339999999, + "lng": -0.5705307, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '28 m', 'value': 28}, - 'duration': {'text': '1 min', 'value': 45}, - 'end_location': { - 'lat': 44.85245620000001, - 'lng': -0.5681259, + "distance": {"text": "28 m", "value": 28}, + "duration": {"text": "1 min", "value": 45}, + "end_location": { + "lat": 44.85245620000001, + "lng": -0.5681259, }, - 'html_instructions': 'Turn left onto ...', - 'maneuver': 'turn-left', - 'polyline': {'points': '_fwpGz{mBGLADGPCFEN'}, - 'start_location': { - 'lat': 44.8523224, - 'lng': -0.5678223, + "html_instructions": "Turn left onto ...", + "maneuver": "turn-left", + "polyline": {"points": "_fwpGz{mBGLADGPCFEN"}, + "start_location": { + "lat": 44.8523224, + "lng": -0.5678223, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.2 km', 'value': 176}, - 'duration': {'text': '1 min', 'value': 31}, - 'end_location': {'lat': 44.8536857, 'lng': -0.5667282}, - 'html_instructions': 'Turn right onto ...', - 'maneuver': 'turn-right', - 'polyline': { - 'points': '{fwpGx}mB_@c@mAuAOQi@m@m@y@_@c@', + "distance": {"text": "0.2 km", "value": 176}, + "duration": {"text": "1 min", "value": 31}, + "end_location": {"lat": 44.8536857, "lng": -0.5667282}, + "html_instructions": "Turn right onto ...", + "maneuver": "turn-right", + "polyline": { + "points": "{fwpGx}mB_@c@mAuAOQi@m@m@y@_@c@", }, - 'start_location': { - 'lat': 44.85245620000001, - 'lng': -0.5681259, + "start_location": { + "lat": 44.85245620000001, + "lng": -0.5681259, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.2 km', 'value': 172}, - 'duration': {'text': '1 min', 'value': 28}, - 'end_location': {'lat': 44.8547766, 'lng': -0.5682825}, - 'html_instructions': 'Turn left onto ... ', - 'maneuver': 'turn-left', - 'polyline': {'points': 'qnwpG`umBW`@UkDtF'}, - 'start_location': { - 'lat': 44.8536857, - 'lng': -0.5667282, + "distance": {"text": "0.2 km", "value": 172}, + "duration": {"text": "1 min", "value": 28}, + "end_location": {"lat": 44.8547766, "lng": -0.5682825}, + "html_instructions": "Turn left onto ... ", + "maneuver": "turn-left", + "polyline": {"points": "qnwpG`umBW`@UkDtF"}, + "start_location": { + "lat": 44.8536857, + "lng": -0.5667282, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '0.1 km', 'value': 101}, - 'duration': {'text': '1 min', 'value': 17}, - 'end_location': {'lat': 44.8554284, 'lng': -0.5673822}, - 'html_instructions': 'Turn right onto ...', - 'maneuver': 'turn-right', - 'polyline': {'points': 'kuwpGv~mBa@q@cA_B[a@'}, - 'start_location': { - 'lat': 44.8547766, - 'lng': -0.5682825, + "distance": {"text": "0.1 km", "value": 101}, + "duration": {"text": "1 min", "value": 17}, + "end_location": {"lat": 44.8554284, "lng": -0.5673822}, + "html_instructions": "Turn right onto ...", + "maneuver": "turn-right", + "polyline": {"points": "kuwpGv~mBa@q@cA_B[a@"}, + "start_location": { + "lat": 44.8547766, + "lng": -0.5682825, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, { - 'distance': {'text': '15 m', 'value': 15}, - 'duration': {'text': '1 min', 'value': 3}, - 'end_location': { - 'lat': 44.85540839999999, - 'lng': -0.5672105, + "distance": {"text": "15 m", "value": 15}, + "duration": {"text": "1 min", "value": 3}, + "end_location": { + "lat": 44.85540839999999, + "lng": -0.5672105, }, - 'html_instructions': 'Turn right onto ...', - 'maneuver': 'turn-right', - 'polyline': {'points': 'mywpGbymBBC@C?E?C?E?EAC'}, - 'start_location': { - 'lat': 44.8554284, - 'lng': -0.5673822, + "html_instructions": "Turn right onto ...", + "maneuver": "turn-right", + "polyline": {"points": "mywpGbymBBC@C?E?C?E?EAC"}, + "start_location": { + "lat": 44.8554284, + "lng": -0.5673822, }, - 'travel_mode': 'BICYCLING', + "travel_mode": "BICYCLING", }, ], - 'traffic_speed_entry': [], - 'via_waypoint': [], + "traffic_speed_entry": [], + "via_waypoint": [], }, ], - 'overview_polyline': { - 'points': '}tspGxknBUoGi@LcDVe@_CW{Ba@sC[eA_@} ...', + "overview_polyline": { + "points": "}tspGxknBUoGi@LcDVe@_CW{Ba@sC[eA_@} ...", }, - 'summary': 'Quai des Chartrons', - 'warnings': ['Bicycling directions are in beta ...'], - 'waypoint_order': [], + "summary": "Quai des Chartrons", + "warnings": ["Bicycling directions are in beta ..."], + "waypoint_order": [], }, ] @@ -650,9 +650,9 @@ class TestSyncWithGoogleMaps: def directions(_self, *_args, **_kwargs): return api_response - monkeypatch.setattr(googlemaps.Client, 'directions', directions) + monkeypatch.setattr(googlemaps.Client, "directions", directions) - @pytest.mark.usefixtures('_fake_google_api') + @pytest.mark.usefixtures("_fake_google_api") def test_sync_instances_with_google_maps(self, db_session, path): """Call the method for a `Path` object without Google data.""" path.bicycle_distance = None @@ -665,7 +665,7 @@ class TestSyncWithGoogleMaps: assert path.bicycle_duration == 596 assert path._directions is not None - @pytest.mark.usefixtures('_fake_google_api') + @pytest.mark.usefixtures("_fake_google_api") def test_repeated_sync_instances_with_google_maps(self, db_session, path): """Call the method for a `Path` object with Google data. diff --git a/tests/db/test_addresses_pixels.py b/tests/db/test_addresses_pixels.py index a98a0a6..9b38caa 100644 --- a/tests/db/test_addresses_pixels.py +++ b/tests/db/test_addresses_pixels.py @@ -60,7 +60,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_pixels_to_addresses_via_address_id_city_id', + match="fk_addresses_pixels_to_addresses_via_address_id_city_id", ): db_session.execute(stmt) @@ -81,7 +81,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_pixels_to_addresses_via_address_id_city_id', + match="fk_addresses_pixels_to_addresses_via_address_id_city_id", ): db_session.execute(stmt) @@ -102,7 +102,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_pixels_to_grids_via_grid_id_city_id', + match="fk_addresses_pixels_to_grids_via_grid_id_city_id", ): db_session.execute(stmt) @@ -116,7 +116,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_addresses_pixels_to_pixels_via_pixel_id_grid_id', + match="fk_addresses_pixels_to_pixels_via_pixel_id_grid_id", ): db_session.execute(stmt) @@ -131,5 +131,5 @@ class TestConstraints: db_session.add(another_assoc) - with pytest.raises(sa_exc.IntegrityError, match='duplicate key value'): + with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"): db_session.commit() diff --git a/tests/db/test_cities.py b/tests/db/test_cities.py index 193b80d..85a2a99 100644 --- a/tests/db/test_cities.py +++ b/tests/db/test_cities.py @@ -17,7 +17,7 @@ class TestSpecialMethods: """`City` has a non-literal text representation.""" result = repr(city) - assert result == f'' + assert result == f"" @pytest.mark.db @@ -43,8 +43,8 @@ class TestProperties: result = city.center assert isinstance(result, utils.Location) - assert result.latitude == pytest.approx(city_data['center_latitude']) - assert result.longitude == pytest.approx(city_data['center_longitude']) + assert result.latitude == pytest.approx(city_data["center_latitude"]) + assert result.longitude == pytest.approx(city_data["center_longitude"]) def test_center_is_cached(self, city): """Test `City.center` property.""" @@ -58,8 +58,8 @@ class TestProperties: result = city.northeast assert isinstance(result, utils.Location) - assert result.latitude == pytest.approx(city_data['northeast_latitude']) - assert result.longitude == pytest.approx(city_data['northeast_longitude']) + assert result.latitude == pytest.approx(city_data["northeast_latitude"]) + assert result.longitude == pytest.approx(city_data["northeast_longitude"]) def test_northeast_is_cached(self, city): """Test `City.northeast` property.""" @@ -73,8 +73,8 @@ class TestProperties: result = city.southwest assert isinstance(result, utils.Location) - assert result.latitude == pytest.approx(city_data['southwest_latitude']) - assert result.longitude == pytest.approx(city_data['southwest_longitude']) + assert result.latitude == pytest.approx(city_data["southwest_latitude"]) + assert result.longitude == pytest.approx(city_data["southwest_longitude"]) def test_southwest_is_cached(self, city): """Test `City.southwest` property.""" diff --git a/tests/db/test_couriers.py b/tests/db/test_couriers.py index 157aaa7..531750d 100644 --- a/tests/db/test_couriers.py +++ b/tests/db/test_couriers.py @@ -17,7 +17,7 @@ class TestSpecialMethods: """`Courier` has a non-literal text representation.""" result = repr(courier) - assert result == f'' + assert result == f"" @pytest.mark.db @@ -36,10 +36,10 @@ class TestConstraints: def test_invalid_vehicle(self, db_session, courier): """Insert an instance with invalid data.""" - courier.vehicle = 'invalid' + courier.vehicle = "invalid" db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='available_vehicle_types'): + with pytest.raises(sa_exc.IntegrityError, match="available_vehicle_types"): db_session.commit() def test_negative_speed(self, db_session, courier): @@ -47,7 +47,7 @@ class TestConstraints: courier.historic_speed = -1 db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='realistic_speed'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_speed"): db_session.commit() def test_unrealistic_speed(self, db_session, courier): @@ -55,7 +55,7 @@ class TestConstraints: courier.historic_speed = 999 db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='realistic_speed'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_speed"): db_session.commit() def test_negative_capacity(self, db_session, courier): @@ -63,7 +63,7 @@ class TestConstraints: courier.capacity = -1 db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='capacity_under_200_liters'): + with pytest.raises(sa_exc.IntegrityError, match="capacity_under_200_liters"): db_session.commit() def test_too_much_capacity(self, db_session, courier): @@ -71,7 +71,7 @@ class TestConstraints: courier.capacity = 999 db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='capacity_under_200_liters'): + with pytest.raises(sa_exc.IntegrityError, match="capacity_under_200_liters"): db_session.commit() def test_negative_pay_per_hour(self, db_session, courier): @@ -79,7 +79,7 @@ class TestConstraints: courier.pay_per_hour = -1 db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='realistic_pay_per_hour'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_pay_per_hour"): db_session.commit() def test_too_much_pay_per_hour(self, db_session, courier): @@ -87,7 +87,7 @@ class TestConstraints: courier.pay_per_hour = 9999 db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='realistic_pay_per_hour'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_pay_per_hour"): db_session.commit() def test_negative_pay_per_order(self, db_session, courier): @@ -95,7 +95,7 @@ class TestConstraints: courier.pay_per_order = -1 db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='realistic_pay_per_order'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_pay_per_order"): db_session.commit() def test_too_much_pay_per_order(self, db_session, courier): @@ -103,5 +103,5 @@ class TestConstraints: courier.pay_per_order = 999 db_session.add(courier) - with pytest.raises(sa_exc.IntegrityError, match='realistic_pay_per_order'): + with pytest.raises(sa_exc.IntegrityError, match="realistic_pay_per_order"): db_session.commit() diff --git a/tests/db/test_customer.py b/tests/db/test_customer.py index 538fb90..761ed31 100644 --- a/tests/db/test_customer.py +++ b/tests/db/test_customer.py @@ -16,7 +16,7 @@ class TestSpecialMethods: """`Customer` has a non-literal text representation.""" result = repr(customer) - assert result == f'' + assert result == f"" @pytest.mark.db diff --git a/tests/db/test_forecasts.py b/tests/db/test_forecasts.py index 763f05e..cbc9662 100644 --- a/tests/db/test_forecasts.py +++ b/tests/db/test_forecasts.py @@ -11,7 +11,7 @@ from tests import config as test_config from velofy import db -MODEL = 'hets' +MODEL = "hets" @pytest.fixture @@ -52,7 +52,7 @@ class TestSpecialMethods: assert ( result - == f'' # noqa:E501 + == f"" # noqa:E501 ) @@ -80,11 +80,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_forecasts_to_pixels_via_pixel_id', + match="fk_forecasts_to_pixels_via_pixel_id", ): db_session.execute(stmt) - @pytest.mark.parametrize('hour', [10, 23]) + @pytest.mark.parametrize("hour", [10, 23]) def test_invalid_start_at_outside_operating_hours( self, db_session, @@ -102,7 +102,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='within_operating_hours', + match="within_operating_hours", ): db_session.commit() @@ -113,7 +113,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='must_be_quarters_of_the_hour', + match="must_be_quarters_of_the_hour", ): db_session.commit() @@ -124,7 +124,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='no_seconds', + match="no_seconds", ): db_session.commit() @@ -135,11 +135,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='no_microseconds', + match="no_microseconds", ): db_session.commit() - @pytest.mark.parametrize('value', [-1, 0]) + @pytest.mark.parametrize("value", [-1, 0]) def test_positive_time_step(self, db_session, forecast, value): """Insert an instance with invalid data.""" forecast.time_step = value @@ -147,11 +147,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='time_step_must_be_positive', + match="time_step_must_be_positive", ): db_session.commit() - @pytest.mark.parametrize('value', [-1, 0]) + @pytest.mark.parametrize("value", [-1, 0]) def test_positive_train_horizon(self, db_session, forecast, value): """Insert an instance with invalid data.""" forecast.train_horizon = value @@ -159,7 +159,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='training_horizon_must_be_positive', + match="training_horizon_must_be_positive", ): db_session.commit() @@ -170,7 +170,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='actuals_must_be_non_negative', + match="actuals_must_be_non_negative", ): db_session.commit() @@ -196,7 +196,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ci_upper_and_lower_bounds', + match="ci_upper_and_lower_bounds", ): db_session.commit() @@ -209,7 +209,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ci_upper_and_lower_bounds', + match="ci_upper_and_lower_bounds", ): db_session.commit() @@ -222,7 +222,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ci_upper_and_lower_bounds', + match="ci_upper_and_lower_bounds", ): db_session.commit() @@ -235,7 +235,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ci_upper_and_lower_bounds', + match="ci_upper_and_lower_bounds", ): db_session.commit() @@ -249,7 +249,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='prediction_must_be_within_ci', + match="prediction_must_be_within_ci", ): db_session.commit() @@ -267,7 +267,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='prediction_must_be_within_ci', + match="prediction_must_be_within_ci", ): db_session.commit() @@ -281,7 +281,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='prediction_must_be_within_ci', + match="prediction_must_be_within_ci", ): db_session.commit() @@ -299,7 +299,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='prediction_must_be_within_ci', + match="prediction_must_be_within_ci", ): db_session.commit() @@ -313,7 +313,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='prediction_must_be_within_ci', + match="prediction_must_be_within_ci", ): db_session.commit() @@ -331,7 +331,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='prediction_must_be_within_ci', + match="prediction_must_be_within_ci", ): db_session.commit() @@ -345,7 +345,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='prediction_must_be_within_ci', + match="prediction_must_be_within_ci", ): db_session.commit() @@ -363,7 +363,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='prediction_must_be_within_ci', + match="prediction_must_be_within_ci", ): db_session.commit() @@ -385,7 +385,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ci_upper_bound_greater_than_lower_bound', + match="ci_upper_bound_greater_than_lower_bound", ): db_session.commit() @@ -407,7 +407,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ci_upper_bound_greater_than_lower_bound', + match="ci_upper_bound_greater_than_lower_bound", ): db_session.commit() @@ -422,7 +422,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ci95_must_be_wider_than_ci80', + match="ci95_must_be_wider_than_ci80", ): db_session.commit() @@ -440,7 +440,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ci95_must_be_wider_than_ci80', + match="ci95_must_be_wider_than_ci80", ): db_session.commit() @@ -464,7 +464,7 @@ class TestConstraints: ) db_session.add(another_forecast) - with pytest.raises(sa_exc.IntegrityError, match='duplicate key value'): + with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"): db_session.commit() @@ -495,16 +495,16 @@ class TestFromDataFrameConstructor: noon_start_at + dt.timedelta(minutes=test_config.LONG_TIME_STEP), ], ) - index.name = 'start_at' + index.name = "start_at" return pd.DataFrame( data={ - 'actual': (11, 12, 13), - 'prediction': (11.3, 12.3, 13.3), - 'low80': (1.123, 1.23, 1.323), - 'high80': (112.34, 123.4, 132.34), - 'low95': (0.1123, 0.123, 0.1323), - 'high95': (1123.45, 1234.5, 1323.45), + "actual": (11, 12, 13), + "prediction": (11.3, 12.3, 13.3), + "low80": (1.123, 1.23, 1.323), + "high80": (112.34, 123.4, 132.34), + "low95": (0.1123, 0.123, 0.1323), + "high95": (1123.45, 1234.5, 1323.45), }, index=index, ) diff --git a/tests/db/test_grids.py b/tests/db/test_grids.py index 5bdee86..f9433c6 100644 --- a/tests/db/test_grids.py +++ b/tests/db/test_grids.py @@ -18,7 +18,7 @@ class TestSpecialMethods: """`Grid` has a non-literal text representation.""" result = repr(grid) - assert result == f'' + assert result == f"" @pytest.mark.db @@ -45,7 +45,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_grids_to_cities_via_city_id', + match="fk_grids_to_cities_via_city_id", ): db_session.execute(stmt) @@ -58,7 +58,7 @@ class TestConstraints: another_grid = db.Grid(city=grid.city, side_length=grid.side_length) db_session.add(another_grid) - with pytest.raises(sa_exc.IntegrityError, match='duplicate key value'): + with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"): db_session.commit() @@ -86,7 +86,7 @@ class TestGridification: query = ( mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501 ) - monkeypatch.setattr(db, 'session', mock) + monkeypatch.setattr(db, "session", mock) return query @@ -205,7 +205,7 @@ class TestGridification: @pytest.mark.db @pytest.mark.no_cover - @pytest.mark.parametrize('side_length', [250, 500, 1_000, 2_000, 4_000, 8_000]) + @pytest.mark.parametrize("side_length", [250, 500, 1_000, 2_000, 4_000, 8_000]) def test_make_random_grids( self, db_session, diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index e794eef..cad9d13 100644 --- a/tests/db/test_orders.py +++ b/tests/db/test_orders.py @@ -22,7 +22,7 @@ class TestSpecialMethods: """`Order` has a non-literal text representation.""" result = repr(order) - assert result == f'' + assert result == f"" @pytest.mark.db @@ -60,7 +60,7 @@ class TestConstraints: # Must delete without ORM as otherwise an UPDATE statement is emitted. stmt = sqla.delete(db.Customer).where(db.Customer.id == order.customer.id) - with pytest.raises(sa_exc.IntegrityError, match='fk_orders_to_customers'): + with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_customers"): db_session.execute(stmt) def test_delete_a_referenced_courier(self, db_session, order): @@ -71,7 +71,7 @@ class TestConstraints: # Must delete without ORM as otherwise an UPDATE statement is emitted. stmt = sqla.delete(db.Courier).where(db.Courier.id == order.courier.id) - with pytest.raises(sa_exc.IntegrityError, match='fk_orders_to_couriers'): + with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_couriers"): db_session.execute(stmt) def test_delete_a_referenced_restaurant(self, db_session, order): @@ -82,7 +82,7 @@ class TestConstraints: # Must delete without ORM as otherwise an UPDATE statement is emitted. stmt = sqla.delete(db.Restaurant).where(db.Restaurant.id == order.restaurant.id) - with pytest.raises(sa_exc.IntegrityError, match='fk_orders_to_restaurants'): + with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_restaurants"): db_session.execute(stmt) def test_change_a_referenced_pickup_address(self, db_session, order, make_address): @@ -97,7 +97,7 @@ class TestConstraints: order.restaurant.address = make_address() db_session.add(order.restaurant.address) - with pytest.raises(sa_exc.IntegrityError, match='fk_orders_to_restaurants'): + with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_restaurants"): db_session.commit() # Here should be a test to check deletion of a referenced pickup address, so @@ -114,7 +114,7 @@ class TestConstraints: # Must delete without ORM as otherwise an UPDATE statement is emitted. stmt = sqla.delete(db.Address).where(db.Address.id == order.delivery_address.id) - with pytest.raises(sa_exc.IntegrityError, match='fk_orders_to_addresses'): + with pytest.raises(sa_exc.IntegrityError, match="fk_orders_to_addresses"): db_session.execute(stmt) def test_ad_hoc_order_with_scheduled_delivery_at(self, db_session, order): @@ -128,7 +128,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='either_ad_hoc_or_scheduled_order', + match="either_ad_hoc_or_scheduled_order", ): db_session.commit() @@ -143,7 +143,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='either_ad_hoc_or_scheduled_order', + match="either_ad_hoc_or_scheduled_order", ): db_session.commit() @@ -155,7 +155,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ad_hoc_orders_within_business_hours', + match="ad_hoc_orders_within_business_hours", ): db_session.commit() @@ -167,7 +167,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='ad_hoc_orders_within_business_hours', + match="ad_hoc_orders_within_business_hours", ): db_session.commit() @@ -182,7 +182,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_within_business_hours', + match="scheduled_orders_within_business_hours", ): db_session.commit() @@ -197,7 +197,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_within_business_hours', + match="scheduled_orders_within_business_hours", ): db_session.commit() @@ -229,11 +229,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_within_business_hours', + match="scheduled_orders_within_business_hours", ): db_session.commit() - @pytest.mark.parametrize('minute', [min_ for min_ in range(60) if min_ % 15 != 0]) + @pytest.mark.parametrize("minute", [min_ for min_ in range(60) if min_ % 15 != 0]) def test_scheduled_order_at_non_quarter_of_an_hour( self, db_session, @@ -254,11 +254,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_must_be_at_quarters_of_an_hour', + match="scheduled_orders_must_be_at_quarters_of_an_hour", ): db_session.commit() - @pytest.mark.parametrize('second', list(range(1, 60))) + @pytest.mark.parametrize("second", list(range(1, 60))) def test_scheduled_order_at_non_quarter_of_an_hour_by_seconds( self, db_session, @@ -280,7 +280,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_must_be_at_quarters_of_an_hour', + match="scheduled_orders_must_be_at_quarters_of_an_hour", ): db_session.commit() @@ -309,7 +309,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='scheduled_orders_not_within_30_minutes', + match="scheduled_orders_not_within_30_minutes", ): db_session.commit() @@ -326,7 +326,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='only_cancelled_orders_may_have_cancelled_at', + match="only_cancelled_orders_may_have_cancelled_at", ): db_session.commit() @@ -340,11 +340,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='cancelled_orders_must_not_be_delivered', + match="cancelled_orders_must_not_be_delivered", ): db_session.commit() - @pytest.mark.parametrize('duration', [-1, 2701]) + @pytest.mark.parametrize("duration", [-1, 2701]) def test_estimated_prep_duration_out_of_range(self, db_session, order, duration): """Insert an instance with invalid data.""" order.estimated_prep_duration = duration @@ -352,11 +352,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='between_0_and_2700', + match="between_0_and_2700", ): db_session.commit() - @pytest.mark.parametrize('duration', [1, 59, 119, 2699]) + @pytest.mark.parametrize("duration", [1, 59, 119, 2699]) def test_estimated_prep_duration_not_whole_minute( self, db_session, @@ -369,11 +369,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='must_be_whole_minutes', + match="must_be_whole_minutes", ): db_session.commit() - @pytest.mark.parametrize('duration', [-1, 901]) + @pytest.mark.parametrize("duration", [-1, 901]) def test_estimated_prep_buffer_out_of_range(self, db_session, order, duration): """Insert an instance with invalid data.""" order.estimated_prep_buffer = duration @@ -381,11 +381,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='between_0_and_900', + match="between_0_and_900", ): db_session.commit() - @pytest.mark.parametrize('duration', [1, 59, 119, 899]) + @pytest.mark.parametrize("duration", [1, 59, 119, 899]) def test_estimated_prep_buffer_not_whole_minute(self, db_session, order, duration): """Insert an instance with invalid data.""" order.estimated_prep_buffer = duration @@ -393,11 +393,11 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='must_be_whole_minutes', + match="must_be_whole_minutes", ): db_session.commit() - @pytest.mark.parametrize('utilization', [-1, 101]) + @pytest.mark.parametrize("utilization", [-1, 101]) def test_utilization_out_of_range(self, db_session, order, utilization): """Insert an instance with invalid data.""" order.utilization = utilization @@ -405,22 +405,22 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='between_0_and_100', + match="between_0_and_100", ): db_session.commit() @pytest.mark.parametrize( - 'column', + "column", [ - 'scheduled_delivery_at', - 'cancelled_at', - 'restaurant_notified_at', - 'restaurant_confirmed_at', - 'estimated_prep_duration', - 'dispatch_at', - 'courier_notified_at', - 'courier_accepted_at', - 'left_pickup_at', + "scheduled_delivery_at", + "cancelled_at", + "restaurant_notified_at", + "restaurant_confirmed_at", + "estimated_prep_duration", + "dispatch_at", + "courier_notified_at", + "courier_accepted_at", + "left_pickup_at", ], ) def test_unset_timestamp_column_not_marked_as_uncorrected( @@ -438,25 +438,25 @@ class TestConstraints: setattr(order, column, None) # Setting both the timestamp and its correction column to NULL is allowed. - setattr(order, f'{column}_corrected', None) + setattr(order, f"{column}_corrected", None) db_session.add(order) db_session.commit() # Also, an unset timestamp column may always be marked as corrected. - setattr(order, f'{column}_corrected', True) + setattr(order, f"{column}_corrected", True) db_session.add(order) db_session.commit() # Without a timestamp set, a column may not be marked as uncorrected. - setattr(order, f'{column}_corrected', False) + setattr(order, f"{column}_corrected", False) db_session.add(order) with pytest.raises( sa_exc.IntegrityError, - match='corrections_only_for_set_value', + match="corrections_only_for_set_value", ): db_session.commit() @@ -473,7 +473,7 @@ class TestConstraints: self.test_unset_timestamp_column_not_marked_as_uncorrected( db_session, order, - 'pickup_at', + "pickup_at", ) def test_unset_timestamp_column_not_marked_as_uncorrected_special_case2( @@ -490,21 +490,21 @@ class TestConstraints: self.test_unset_timestamp_column_not_marked_as_uncorrected( db_session, order, - 'delivery_at', + "delivery_at", ) @pytest.mark.parametrize( - 'column', + "column", [ - 'restaurant_notified_at', - 'restaurant_confirmed_at', - 'estimated_prep_duration', - 'dispatch_at', - 'courier_notified_at', - 'courier_accepted_at', - 'pickup_at', - 'left_pickup_at', - 'delivery_at', + "restaurant_notified_at", + "restaurant_confirmed_at", + "estimated_prep_duration", + "dispatch_at", + "courier_notified_at", + "courier_accepted_at", + "pickup_at", + "left_pickup_at", + "delivery_at", ], ) def test_set_timestamp_column_is_not_unmarked( @@ -523,24 +523,24 @@ class TestConstraints: # A set timestamp may be marked as either corrected or uncorrected. - setattr(order, f'{column}_corrected', True) + setattr(order, f"{column}_corrected", True) db_session.add(order) db_session.commit() - setattr(order, f'{column}_corrected', False) + setattr(order, f"{column}_corrected", False) db_session.add(order) db_session.commit() # A set timestamp may not be left unmarked. - setattr(order, f'{column}_corrected', None) + setattr(order, f"{column}_corrected", None) db_session.add(order) with pytest.raises( sa_exc.IntegrityError, - match='corrections_only_for_set_value', + match="corrections_only_for_set_value", ): db_session.commit() @@ -556,7 +556,7 @@ class TestConstraints: self.test_set_timestamp_column_is_not_unmarked( db_session, pre_order, - 'scheduled_delivery_at', + "scheduled_delivery_at", ) def test_set_timestamp_column_is_not_unmarked_special_case2( @@ -579,54 +579,54 @@ class TestConstraints: self.test_set_timestamp_column_is_not_unmarked( db_session, order, - 'cancelled_at', + "cancelled_at", ) @pytest.mark.parametrize( - 'comparison', + "comparison", [ - 'placed_at < first_estimated_delivery_at', - 'placed_at < restaurant_notified_at', - 'placed_at < restaurant_confirmed_at', - 'placed_at < dispatch_at', - 'placed_at < courier_notified_at', - 'placed_at < courier_accepted_at', - 'placed_at < reached_pickup_at', - 'placed_at < pickup_at', - 'placed_at < left_pickup_at', - 'placed_at < reached_delivery_at', - 'placed_at < delivery_at', - 'restaurant_notified_at < restaurant_confirmed_at', - 'restaurant_notified_at < pickup_at', - 'restaurant_confirmed_at < pickup_at', - 'dispatch_at < courier_notified_at', - 'dispatch_at < courier_accepted_at', - 'dispatch_at < reached_pickup_at', - 'dispatch_at < pickup_at', - 'dispatch_at < left_pickup_at', - 'dispatch_at < reached_delivery_at', - 'dispatch_at < delivery_at', - 'courier_notified_at < courier_accepted_at', - 'courier_notified_at < reached_pickup_at', - 'courier_notified_at < pickup_at', - 'courier_notified_at < left_pickup_at', - 'courier_notified_at < reached_delivery_at', - 'courier_notified_at < delivery_at', - 'courier_accepted_at < reached_pickup_at', - 'courier_accepted_at < pickup_at', - 'courier_accepted_at < left_pickup_at', - 'courier_accepted_at < reached_delivery_at', - 'courier_accepted_at < delivery_at', - 'reached_pickup_at < pickup_at', - 'reached_pickup_at < left_pickup_at', - 'reached_pickup_at < reached_delivery_at', - 'reached_pickup_at < delivery_at', - 'pickup_at < left_pickup_at', - 'pickup_at < reached_delivery_at', - 'pickup_at < delivery_at', - 'left_pickup_at < reached_delivery_at', - 'left_pickup_at < delivery_at', - 'reached_delivery_at < delivery_at', + "placed_at < first_estimated_delivery_at", + "placed_at < restaurant_notified_at", + "placed_at < restaurant_confirmed_at", + "placed_at < dispatch_at", + "placed_at < courier_notified_at", + "placed_at < courier_accepted_at", + "placed_at < reached_pickup_at", + "placed_at < pickup_at", + "placed_at < left_pickup_at", + "placed_at < reached_delivery_at", + "placed_at < delivery_at", + "restaurant_notified_at < restaurant_confirmed_at", + "restaurant_notified_at < pickup_at", + "restaurant_confirmed_at < pickup_at", + "dispatch_at < courier_notified_at", + "dispatch_at < courier_accepted_at", + "dispatch_at < reached_pickup_at", + "dispatch_at < pickup_at", + "dispatch_at < left_pickup_at", + "dispatch_at < reached_delivery_at", + "dispatch_at < delivery_at", + "courier_notified_at < courier_accepted_at", + "courier_notified_at < reached_pickup_at", + "courier_notified_at < pickup_at", + "courier_notified_at < left_pickup_at", + "courier_notified_at < reached_delivery_at", + "courier_notified_at < delivery_at", + "courier_accepted_at < reached_pickup_at", + "courier_accepted_at < pickup_at", + "courier_accepted_at < left_pickup_at", + "courier_accepted_at < reached_delivery_at", + "courier_accepted_at < delivery_at", + "reached_pickup_at < pickup_at", + "reached_pickup_at < left_pickup_at", + "reached_pickup_at < reached_delivery_at", + "reached_pickup_at < delivery_at", + "pickup_at < left_pickup_at", + "pickup_at < reached_delivery_at", + "pickup_at < delivery_at", + "left_pickup_at < reached_delivery_at", + "left_pickup_at < delivery_at", + "reached_delivery_at < delivery_at", ], ) def test_timestamps_unordered( @@ -640,17 +640,17 @@ class TestConstraints: There are two special cases for this test case below, where other attributes on `order` must be unset. """ - smaller, bigger = comparison.split(' < ') + smaller, bigger = comparison.split(" < ") assert smaller is not None violating_timestamp = getattr(order, smaller) - dt.timedelta(seconds=1) setattr(order, bigger, violating_timestamp) - setattr(order, f'{bigger}_corrected', False) + setattr(order, f"{bigger}_corrected", False) db_session.add(order) - with pytest.raises(sa_exc.IntegrityError, match='ordered_timestamps'): + with pytest.raises(sa_exc.IntegrityError, match="ordered_timestamps"): db_session.commit() def test_timestamps_unordered_scheduled(self, db_session, pre_order): @@ -664,22 +664,22 @@ class TestConstraints: self.test_timestamps_unordered( db_session, pre_order, - 'placed_at < scheduled_delivery_at', + "placed_at < scheduled_delivery_at", ) @pytest.mark.parametrize( - 'comparison', + "comparison", [ - 'placed_at < cancelled_at', - 'restaurant_notified_at < cancelled_at', - 'restaurant_confirmed_at < cancelled_at', - 'dispatch_at < cancelled_at', - 'courier_notified_at < cancelled_at', - 'courier_accepted_at < cancelled_at', - 'reached_pickup_at < cancelled_at', - 'pickup_at < cancelled_at', - 'left_pickup_at < cancelled_at', - 'reached_delivery_at < cancelled_at', + "placed_at < cancelled_at", + "restaurant_notified_at < cancelled_at", + "restaurant_confirmed_at < cancelled_at", + "dispatch_at < cancelled_at", + "courier_notified_at < cancelled_at", + "courier_accepted_at < cancelled_at", + "reached_pickup_at < cancelled_at", + "pickup_at < cancelled_at", + "left_pickup_at < cancelled_at", + "reached_delivery_at < cancelled_at", ], ) def test_timestamps_unordered_cancelled( @@ -758,23 +758,23 @@ class TestProperties: assert result is False @pytest.mark.parametrize( - 'column', + "column", [ - 'scheduled_delivery_at', - 'cancelled_at', - 'restaurant_notified_at', - 'restaurant_confirmed_at', - 'dispatch_at', - 'courier_notified_at', - 'courier_accepted_at', - 'pickup_at', - 'left_pickup_at', - 'delivery_at', + "scheduled_delivery_at", + "cancelled_at", + "restaurant_notified_at", + "restaurant_confirmed_at", + "dispatch_at", + "courier_notified_at", + "courier_accepted_at", + "pickup_at", + "left_pickup_at", + "delivery_at", ], ) def test_is_corrected(self, order, column): """Test `Order.corrected` property.""" - setattr(order, f'{column}_corrected', True) + setattr(order, f"{column}_corrected", True) result = order.corrected @@ -784,14 +784,14 @@ class TestProperties: """Test `Order.time_to_accept` property.""" order.dispatch_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_to_accept) def test_time_to_accept_no_courier_accepted(self, order): """Test `Order.time_to_accept` property.""" order.courier_accepted_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_to_accept) def test_time_to_accept_success(self, order): @@ -804,14 +804,14 @@ class TestProperties: """Test `Order.time_to_react` property.""" order.courier_notified_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_to_react) def test_time_to_react_no_courier_accepted(self, order): """Test `Order.time_to_react` property.""" order.courier_accepted_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_to_react) def test_time_to_react_success(self, order): @@ -824,14 +824,14 @@ class TestProperties: """Test `Order.time_to_pickup` property.""" order.reached_pickup_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_to_pickup) def test_time_to_pickup_no_courier_accepted(self, order): """Test `Order.time_to_pickup` property.""" order.courier_accepted_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_to_pickup) def test_time_to_pickup_success(self, order): @@ -844,14 +844,14 @@ class TestProperties: """Test `Order.time_at_pickup` property.""" order.reached_pickup_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_at_pickup) def test_time_at_pickup_no_pickup_at(self, order): """Test `Order.time_at_pickup` property.""" order.pickup_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_at_pickup) def test_time_at_pickup_success(self, order): @@ -864,14 +864,14 @@ class TestProperties: """Test `Order.scheduled_pickup_at` property.""" order.restaurant_notified_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.scheduled_pickup_at) def test_scheduled_pickup_at_no_est_prep_duration(self, order): """Test `Order.scheduled_pickup_at` property.""" order.estimated_prep_duration = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.scheduled_pickup_at) def test_scheduled_pickup_at_success(self, order): @@ -956,14 +956,14 @@ class TestProperties: """Test `Order.time_to_delivery` property.""" order.reached_delivery_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_to_delivery) def test_time_to_delivery_no_pickup_at(self, order): """Test `Order.time_to_delivery` property.""" order.pickup_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_to_delivery) def test_time_to_delivery_success(self, order): @@ -976,14 +976,14 @@ class TestProperties: """Test `Order.time_at_delivery` property.""" order.reached_delivery_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_at_delivery) def test_time_at_delivery_no_delivery_at(self, order): """Test `Order.time_at_delivery` property.""" order.delivery_at = None - with pytest.raises(RuntimeError, match='not set'): + with pytest.raises(RuntimeError, match="not set"): int(order.time_at_delivery) def test_time_at_delivery_success(self, order): @@ -1011,7 +1011,7 @@ class TestProperties: def test_ad_hoc_order_cannot_be_early(self, order): """Test `Order.delivery_early` property.""" # By default, the `OrderFactory` creates ad-hoc orders. - with pytest.raises(AttributeError, match='scheduled'): + with pytest.raises(AttributeError, match="scheduled"): int(order.delivery_early) def test_scheduled_order_delivered_early(self, make_order): @@ -1037,7 +1037,7 @@ class TestProperties: def test_ad_hoc_order_cannot_be_late(self, order): """Test Order.delivery_late property.""" # By default, the `OrderFactory` creates ad-hoc orders. - with pytest.raises(AttributeError, match='scheduled'): + with pytest.raises(AttributeError, match="scheduled"): int(order.delivery_late) def test_scheduled_order_delivered_late(self, make_order): @@ -1064,14 +1064,14 @@ class TestProperties: """Test `Order.total_time` property.""" order = make_order(scheduled=True) - with pytest.raises(AttributeError, match='Scheduled'): + with pytest.raises(AttributeError, match="Scheduled"): int(order.total_time) def test_no_total_time_for_cancelled_order(self, make_order): """Test `Order.total_time` property.""" order = make_order(cancel_before_pickup=True) - with pytest.raises(RuntimeError, match='Cancelled'): + with pytest.raises(RuntimeError, match="Cancelled"): int(order.total_time) def test_total_time_success(self, order): diff --git a/tests/db/test_pixels.py b/tests/db/test_pixels.py index a1e2b5e..a7df8c9 100644 --- a/tests/db/test_pixels.py +++ b/tests/db/test_pixels.py @@ -18,7 +18,7 @@ class TestSpecialMethods: """`Pixel` has a non-literal text representation.""" result = repr(pixel) - assert result == f'' + assert result == f"" @pytest.mark.db @@ -45,7 +45,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_pixels_to_grids_via_grid_id', + match="fk_pixels_to_grids_via_grid_id", ): db_session.execute(stmt) @@ -54,7 +54,7 @@ class TestConstraints: pixel.n_x = -1 db_session.add(pixel) - with pytest.raises(sa_exc.IntegrityError, match='n_x_is_positive'): + with pytest.raises(sa_exc.IntegrityError, match="n_x_is_positive"): db_session.commit() def test_negative_n_y(self, db_session, pixel): @@ -62,7 +62,7 @@ class TestConstraints: pixel.n_y = -1 db_session.add(pixel) - with pytest.raises(sa_exc.IntegrityError, match='n_y_is_positive'): + with pytest.raises(sa_exc.IntegrityError, match="n_y_is_positive"): db_session.commit() def test_non_unique_coordinates_within_a_grid(self, db_session, pixel): @@ -70,7 +70,7 @@ class TestConstraints: another_pixel = db.Pixel(grid=pixel.grid, n_x=pixel.n_x, n_y=pixel.n_y) db_session.add(another_pixel) - with pytest.raises(sa_exc.IntegrityError, match='duplicate key value'): + with pytest.raises(sa_exc.IntegrityError, match="duplicate key value"): db_session.commit() @@ -125,16 +125,16 @@ class TestProperties: mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501 ) query.return_value = [restaurant] - monkeypatch.setattr(db, 'session', mock) + monkeypatch.setattr(db, "session", mock) - @pytest.mark.usefixtures('_restaurants_mock') + @pytest.mark.usefixtures("_restaurants_mock") def test_restaurants(self, pixel, restaurant): """Test `Pixel.restaurants` property.""" result = pixel.restaurants assert result == [restaurant] - @pytest.mark.usefixtures('_restaurants_mock') + @pytest.mark.usefixtures("_restaurants_mock") def test_restaurants_is_cached(self, pixel): """Test `Pixel.restaurants` property.""" result1 = pixel.restaurants diff --git a/tests/db/test_restaurants.py b/tests/db/test_restaurants.py index 6ed14e0..9b07932 100644 --- a/tests/db/test_restaurants.py +++ b/tests/db/test_restaurants.py @@ -18,7 +18,7 @@ class TestSpecialMethods: """`Restaurant` has a non-literal text representation.""" result = repr(restaurant) - assert result == f'' + assert result == f"" @pytest.mark.db @@ -45,7 +45,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='fk_restaurants_to_addresses_via_address_id', + match="fk_restaurants_to_addresses_via_address_id", ): db_session.execute(stmt) @@ -56,7 +56,7 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='realistic_estimated_prep_duration', + match="realistic_estimated_prep_duration", ): db_session.commit() @@ -67,6 +67,6 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='realistic_estimated_prep_duration', + match="realistic_estimated_prep_duration", ): db_session.commit() diff --git a/tests/db/utils/test_locations.py b/tests/db/utils/test_locations.py index 204340b..76bae4e 100644 --- a/tests/db/utils/test_locations.py +++ b/tests/db/utils/test_locations.py @@ -8,7 +8,7 @@ from velofy.db import utils # All tests take place in Paris. MIN_EASTING, MAX_EASTING = 443_100, 461_200 MIN_NORTHING, MAX_NORTHING = 5_407_200, 5_416_800 -ZONE = '31U' +ZONE = "31U" @pytest.fixture @@ -52,8 +52,8 @@ class TestSpecialMethods: """The text representation is a non-literal.""" result = repr(location) - assert result.startswith('') + assert result.startswith("") @pytest.mark.e2e def test_coordinates_in_the_text_representation(self, location): @@ -64,7 +64,7 @@ class TestSpecialMethods: """ result = repr(location) - parts = result.split(' ') + parts = result.split(" ") zone = parts[1] easting = int(parts[2]) northing = int(parts[3][:-1]) # strip the ending ">" @@ -85,7 +85,7 @@ class TestSpecialMethods: faraway_location, ): """Test `Location.__eq__()`.""" - with pytest.raises(ValueError, match='must be in the same zone'): + with pytest.raises(ValueError, match="must be in the same zone"): bool(location == faraway_location) def test_compare_utm_coordinates_to_equal_coordinates(self, location, address): @@ -156,7 +156,7 @@ class TestProperties: result = location.zone_details zone, band = result - assert ZONE == f'{zone}{band}' + assert ZONE == f"{zone}{band}" class TestRelateTo: @@ -166,12 +166,12 @@ class TestRelateTo: """The `.relate_to()` method must only be run once.""" location.relate_to(origin) - with pytest.raises(RuntimeError, match='once'): + with pytest.raises(RuntimeError, match="once"): location.relate_to(origin) def test_call_relate_to_with_wrong_other_type(self, location): """`other` must be another `Location`.""" - with pytest.raises(TypeError, match='Location'): + with pytest.raises(TypeError, match="Location"): location.relate_to(object()) def test_call_relate_to_with_far_away_other( @@ -180,17 +180,17 @@ class TestRelateTo: faraway_location, ): """The `other` origin must be in the same UTM zone.""" - with pytest.raises(ValueError, match='must be in the same zone'): + with pytest.raises(ValueError, match="must be in the same zone"): location.relate_to(faraway_location) def test_access_x_without_origin(self, location): """`.relate_to()` must be called before `.x` can be accessed.""" - with pytest.raises(RuntimeError, match='origin to relate to must be set'): + with pytest.raises(RuntimeError, match="origin to relate to must be set"): int(location.x) def test_access_y_without_origin(self, location): """`.relate_to()` must be called before `.y` can be accessed.""" - with pytest.raises(RuntimeError, match='origin to relate to must be set'): + with pytest.raises(RuntimeError, match="origin to relate to must be set"): int(location.y) def test_origin_must_be_lower_left_when_relating_to_oneself(self, location): diff --git a/tests/forecasts/conftest.py b/tests/forecasts/conftest.py index 1143b7d..d5b6e3d 100644 --- a/tests/forecasts/conftest.py +++ b/tests/forecasts/conftest.py @@ -21,11 +21,11 @@ def horizontal_datetime_index(): gen = ( start_at - for start_at in pd.date_range(first_start_at, test_config.END, freq='D') + for start_at in pd.date_range(first_start_at, test_config.END, freq="D") ) index = pd.Index(gen) - index.name = 'start_at' + index.name = "start_at" # Sanity check. # `+1` as both the `START` and `END` day are included. @@ -38,7 +38,7 @@ def horizontal_datetime_index(): @pytest.fixture def horizontal_no_demand(horizontal_datetime_index): """A horizontal time series with order totals: no demand.""" - return pd.Series(0, index=horizontal_datetime_index, name='n_orders') + return pd.Series(0, index=horizontal_datetime_index, name="n_orders") @pytest.fixture @@ -52,7 +52,7 @@ def vertical_datetime_index(): start_ats = pd.date_range( test_config.START, test_config.END, - freq=f'{test_config.LONG_TIME_STEP}min', + freq=f"{test_config.LONG_TIME_STEP}min", ) gen = ( start_at @@ -61,7 +61,7 @@ def vertical_datetime_index(): ) index = pd.Index(gen) - index.name = 'start_at' + index.name = "start_at" # Sanity check: n_days * n_number_of_opening_hours. # `+1` as both the `START` and `END` day are included. @@ -74,7 +74,7 @@ def vertical_datetime_index(): @pytest.fixture def vertical_no_demand(vertical_datetime_index): """A vertical time series with order totals: no demand.""" - return pd.Series(0, index=vertical_datetime_index, name='n_orders') + return pd.Series(0, index=vertical_datetime_index, name="n_orders") @pytest.fixture @@ -107,7 +107,7 @@ def order_totals(good_pixel_id): start_ats = pd.date_range( test_config.START, test_config.END, - freq=f'{test_config.LONG_TIME_STEP}min', + freq=f"{test_config.LONG_TIME_STEP}min", ) gen = ( (pixel_id, start_at) @@ -118,9 +118,9 @@ def order_totals(good_pixel_id): # Re-index `data` filling in `0`s where there is no demand. index = pd.MultiIndex.from_tuples(gen) - index.names = ['pixel_id', 'start_at'] + index.names = ["pixel_id", "start_at"] - df = pd.DataFrame(data={'n_orders': 1}, index=index) + df = pd.DataFrame(data={"n_orders": 1}, index=index) # Sanity check: n_pixels * n_time_steps_per_day * n_days. # `+1` as both the `START` and `END` day are included. diff --git a/tests/forecasts/methods/test_decomposition.py b/tests/forecasts/methods/test_decomposition.py index 3a38c19..c351cda 100644 --- a/tests/forecasts/methods/test_decomposition.py +++ b/tests/forecasts/methods/test_decomposition.py @@ -20,7 +20,7 @@ class TestInvalidArguments: """`stl()` requires a `time_series` without `NaN` values.""" time_series = pd.Series(dtype=float, index=vertical_datetime_index) - with pytest.raises(ValueError, match='`NaN` values'): + with pytest.raises(ValueError, match="`NaN` values"): decomposition.stl( time_series, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -29,17 +29,17 @@ class TestInvalidArguments: def test_ns_not_odd(self, vertical_no_demand): """`ns` must be odd and `>= 7`.""" - with pytest.raises(ValueError, match='`ns`'): + with pytest.raises(ValueError, match="`ns`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, ns=8, ) - @pytest.mark.parametrize('ns', [-99, -1, 1, 5]) + @pytest.mark.parametrize("ns", [-99, -1, 1, 5]) def test_ns_smaller_than_seven(self, vertical_no_demand, ns): """`ns` must be odd and `>= 7`.""" - with pytest.raises(ValueError, match='`ns`'): + with pytest.raises(ValueError, match="`ns`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -55,7 +55,7 @@ class TestInvalidArguments: assert nt > default_nt # sanity check - with pytest.raises(ValueError, match='`nt`'): + with pytest.raises(ValueError, match="`nt`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -63,7 +63,7 @@ class TestInvalidArguments: nt=nt, ) - @pytest.mark.parametrize('nt', [-99, -1, 0, 1, 99, 125]) + @pytest.mark.parametrize("nt", [-99, -1, 0, 1, 99, 125]) def test_nt_not_at_least_the_default(self, vertical_no_demand, nt): """`nt` must be odd and `>= default_nt`.""" # `default_nt` becomes 161. @@ -73,7 +73,7 @@ class TestInvalidArguments: assert nt < default_nt # sanity check - with pytest.raises(ValueError, match='`nt`'): + with pytest.raises(ValueError, match="`nt`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -87,7 +87,7 @@ class TestInvalidArguments: assert nl > test_config.VERTICAL_FREQUENCY_LONG # sanity check - with pytest.raises(ValueError, match='`nl`'): + with pytest.raises(ValueError, match="`nl`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -101,7 +101,7 @@ class TestInvalidArguments: assert nl < test_config.VERTICAL_FREQUENCY_LONG # sanity check - with pytest.raises(ValueError, match='`nl`'): + with pytest.raises(ValueError, match="`nl`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -111,7 +111,7 @@ class TestInvalidArguments: def test_ds_not_zero_or_one(self, vertical_no_demand): """`ds` must be `0` or `1`.""" - with pytest.raises(ValueError, match='`ds`'): + with pytest.raises(ValueError, match="`ds`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -121,7 +121,7 @@ class TestInvalidArguments: def test_dt_not_zero_or_one(self, vertical_no_demand): """`dt` must be `0` or `1`.""" - with pytest.raises(ValueError, match='`dt`'): + with pytest.raises(ValueError, match="`dt`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -131,7 +131,7 @@ class TestInvalidArguments: def test_dl_not_zero_or_one(self, vertical_no_demand): """`dl` must be `0` or `1`.""" - with pytest.raises(ValueError, match='`dl`'): + with pytest.raises(ValueError, match="`dl`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -139,10 +139,10 @@ class TestInvalidArguments: dl=2, ) - @pytest.mark.parametrize('js', [-1, 0]) + @pytest.mark.parametrize("js", [-1, 0]) def test_js_not_positive(self, vertical_no_demand, js): """`js` must be positive.""" - with pytest.raises(ValueError, match='`js`'): + with pytest.raises(ValueError, match="`js`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -150,10 +150,10 @@ class TestInvalidArguments: js=js, ) - @pytest.mark.parametrize('jt', [-1, 0]) + @pytest.mark.parametrize("jt", [-1, 0]) def test_jt_not_positive(self, vertical_no_demand, jt): """`jt` must be positive.""" - with pytest.raises(ValueError, match='`jt`'): + with pytest.raises(ValueError, match="`jt`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -161,10 +161,10 @@ class TestInvalidArguments: jt=jt, ) - @pytest.mark.parametrize('jl', [-1, 0]) + @pytest.mark.parametrize("jl", [-1, 0]) def test_jl_not_positive(self, vertical_no_demand, jl): """`jl` must be positive.""" - with pytest.raises(ValueError, match='`jl`'): + with pytest.raises(ValueError, match="`jl`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -172,10 +172,10 @@ class TestInvalidArguments: jl=jl, ) - @pytest.mark.parametrize('ni', [-1, 0]) + @pytest.mark.parametrize("ni", [-1, 0]) def test_ni_not_positive(self, vertical_no_demand, ni): """`ni` must be positive.""" - with pytest.raises(ValueError, match='`ni`'): + with pytest.raises(ValueError, match="`ni`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -185,7 +185,7 @@ class TestInvalidArguments: def test_no_not_non_negative(self, vertical_no_demand): """`no` must be non-negative.""" - with pytest.raises(ValueError, match='`no`'): + with pytest.raises(ValueError, match="`no`"): decomposition.stl( vertical_no_demand, frequency=test_config.VERTICAL_FREQUENCY_LONG, @@ -207,20 +207,20 @@ class TestValidArguments: ) assert isinstance(result, pd.DataFrame) - assert list(result.columns) == ['seasonal', 'trend', 'residual'] + assert list(result.columns) == ["seasonal", "trend", "residual"] # Run the `stl()` function with all possible combinations of arguments, # including default ones and explicitly set non-default ones. - @pytest.mark.parametrize('nt', [None, 163]) - @pytest.mark.parametrize('nl', [None, 777]) - @pytest.mark.parametrize('ds', [0, 1]) - @pytest.mark.parametrize('dt', [0, 1]) - @pytest.mark.parametrize('dl', [0, 1]) - @pytest.mark.parametrize('js', [None, 1]) - @pytest.mark.parametrize('jt', [None, 1]) - @pytest.mark.parametrize('jl', [None, 1]) - @pytest.mark.parametrize('ni', [2, 3]) - @pytest.mark.parametrize('no', [0, 1]) + @pytest.mark.parametrize("nt", [None, 163]) + @pytest.mark.parametrize("nl", [None, 777]) + @pytest.mark.parametrize("ds", [0, 1]) + @pytest.mark.parametrize("dt", [0, 1]) + @pytest.mark.parametrize("dl", [0, 1]) + @pytest.mark.parametrize("js", [None, 1]) + @pytest.mark.parametrize("jt", [None, 1]) + @pytest.mark.parametrize("jl", [None, 1]) + @pytest.mark.parametrize("ni", [2, 3]) + @pytest.mark.parametrize("no", [0, 1]) def test_decompose_time_series_with_no_demand( self, vertical_no_demand, diff --git a/tests/forecasts/methods/test_predictions.py b/tests/forecasts/methods/test_predictions.py index ac314c9..6dcf2ac 100644 --- a/tests/forecasts/methods/test_predictions.py +++ b/tests/forecasts/methods/test_predictions.py @@ -38,7 +38,7 @@ def forecast_interval(): start_ats = pd.date_range( first_start_at, end_of_day, - freq=f'{test_config.LONG_TIME_STEP}min', + freq=f"{test_config.LONG_TIME_STEP}min", ) gen = ( start_at @@ -47,7 +47,7 @@ def forecast_interval(): ) index = pd.Index(gen) - index.name = 'start_at' + index.name = "start_at" return index @@ -66,14 +66,14 @@ def forecast_time_step(): ) index = pd.Index([start_at]) - index.name = 'start_at' + index.name = "start_at" return index @pytest.mark.r @pytest.mark.parametrize( - 'func', + "func", [arima.predict, ets.predict, extrapolate_season.predict], ) class TestMakePredictions: @@ -88,7 +88,7 @@ class TestMakePredictions: """`training_ts` must not contain `NaN` values.""" vertical_no_demand.iloc[0] = pd.NA - with pytest.raises(ValueError, match='must not contain `NaN`'): + with pytest.raises(ValueError, match="must not contain `NaN`"): func( training_ts=vertical_no_demand, forecast_interval=forecast_interval, @@ -110,11 +110,11 @@ class TestMakePredictions: assert isinstance(result, pd.DataFrame) assert list(result.columns) == [ - 'prediction', - 'low80', - 'high80', - 'low95', - 'high95', + "prediction", + "low80", + "high80", + "low95", + "high95", ] def test_predict_horizontal_time_series_with_no_demand( diff --git a/tests/forecasts/test_models.py b/tests/forecasts/test_models.py index 74784d0..1d62f73 100644 --- a/tests/forecasts/test_models.py +++ b/tests/forecasts/test_models.py @@ -17,7 +17,7 @@ MODELS = ( ) -@pytest.mark.parametrize('model_cls', MODELS) +@pytest.mark.parametrize("model_cls", MODELS) class TestGenericForecastingModelProperties: """Test everything all concrete `*Model`s have in common. @@ -81,12 +81,12 @@ class TestGenericForecastingModelProperties: assert isinstance(result, pd.DataFrame) assert list(result.columns) == [ - 'actual', - 'prediction', - 'low80', - 'high80', - 'low95', - 'high95', + "actual", + "prediction", + "low80", + "high80", + "low95", + "high95", ] @pytest.mark.r @@ -131,8 +131,8 @@ class TestGenericForecastingModelProperties: train_horizon=test_config.LONG_TRAIN_HORIZON, ) - assert not result['actual'].isnull().any() - assert not result['prediction'].isnull().any() + assert not result["actual"].isnull().any() + assert not result["prediction"].isnull().any() @pytest.mark.db @pytest.mark.r diff --git a/tests/forecasts/timify/test_aggregate_orders.py b/tests/forecasts/timify/test_aggregate_orders.py index 0516341..6c60a06 100644 --- a/tests/forecasts/timify/test_aggregate_orders.py +++ b/tests/forecasts/timify/test_aggregate_orders.py @@ -29,7 +29,7 @@ class TestAggregateOrders: query = ( mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501 ) - monkeypatch.setattr(db, 'session', mock) + monkeypatch.setattr(db, "session", mock) return query @@ -95,9 +95,9 @@ class TestAggregateOrders: # The resulting `DataFrame` has 12 rows holding `1`s. assert len(result) == 12 - assert result['n_orders'].min() == 1 - assert result['n_orders'].max() == 1 - assert result['n_orders'].sum() == 12 + assert result["n_orders"].min() == 1 + assert result["n_orders"].max() == 1 + assert result["n_orders"].sum() == 12 def test_evenly_distributed_ad_hoc_orders_with_no_demand_late( self, @@ -130,10 +130,10 @@ class TestAggregateOrders: # Even though there are only 10 orders, there are 12 rows in the `DataFrame`. # That is so as `0`s are filled in for hours without any demand at the end. assert len(result) == 12 - assert result['n_orders'].min() == 0 - assert result['n_orders'].max() == 1 - assert result.iloc[:10]['n_orders'].sum() == 10 - assert result.iloc[10:]['n_orders'].sum() == 0 + assert result["n_orders"].min() == 0 + assert result["n_orders"].max() == 1 + assert result.iloc[:10]["n_orders"].sum() == 10 + assert result.iloc[10:]["n_orders"].sum() == 0 def test_one_ad_hoc_order_every_other_hour( self, @@ -165,9 +165,9 @@ class TestAggregateOrders: # The resulting `DataFrame` has 12 rows, 6 holding `0`s, and 6 holding `1`s. assert len(result) == 12 - assert result['n_orders'].min() == 0 - assert result['n_orders'].max() == 1 - assert result['n_orders'].sum() == 6 + assert result["n_orders"].min() == 0 + assert result["n_orders"].max() == 1 + assert result["n_orders"].sum() == 6 def test_one_ad_hoc_and_one_pre_order( self, @@ -208,9 +208,9 @@ class TestAggregateOrders: # The resulting `DataFrame` has 12 rows, 11 holding `0`s, and one holding a `1`. assert len(result) == 12 - assert result['n_orders'].min() == 0 - assert result['n_orders'].max() == 1 - assert result['n_orders'].sum() == 1 + assert result["n_orders"].min() == 0 + assert result["n_orders"].max() == 1 + assert result["n_orders"].sum() == 1 def test_evenly_distributed_ad_hoc_orders_with_half_hour_time_steps( self, @@ -246,10 +246,10 @@ class TestAggregateOrders: # The resulting `DataFrame` has 24 rows for the 24 30-minute time steps. # The rows' values are `0` and `1` alternating. assert len(result) == 24 - assert result['n_orders'].min() == 0 - assert result['n_orders'].max() == 1 - assert result.iloc[::2]['n_orders'].sum() == 12 - assert result.iloc[1::2]['n_orders'].sum() == 0 + assert result["n_orders"].min() == 0 + assert result["n_orders"].max() == 1 + assert result.iloc[::2]["n_orders"].sum() == 12 + assert result.iloc[1::2]["n_orders"].sum() == 0 def test_ad_hoc_orders_over_two_days( self, @@ -300,9 +300,9 @@ class TestAggregateOrders: # The resulting `DataFrame` has 24 rows, 12 for each day. assert len(result) == 24 - assert result['n_orders'].min() == 0 - assert result['n_orders'].max() == 1 - assert result['n_orders'].sum() == 18 + assert result["n_orders"].min() == 0 + assert result["n_orders"].max() == 1 + assert result["n_orders"].sum() == 18 @pytest.fixture def two_pixel_grid( @@ -403,6 +403,6 @@ class TestAggregateOrders: # The resulting `DataFrame` has 24 rows, 12 for each pixel. assert len(result) == 24 - assert result['n_orders'].min() == 0 - assert result['n_orders'].max() == 2 - assert result['n_orders'].sum() == 30 + assert result["n_orders"].min() == 0 + assert result["n_orders"].max() == 2 + assert result["n_orders"].sum() == 30 diff --git a/tests/forecasts/timify/test_avg_daily_demand.py b/tests/forecasts/timify/test_avg_daily_demand.py index 0969e4d..df41c84 100644 --- a/tests/forecasts/timify/test_avg_daily_demand.py +++ b/tests/forecasts/timify/test_avg_daily_demand.py @@ -43,7 +43,7 @@ class TestAverageDailyDemand: predict_at, ): """Without demand, the average daily demand must be `0.0`.""" - order_history._data.loc[:, 'n_orders'] = 0 + order_history._data.loc[:, "n_orders"] = 0 result = order_history.avg_daily_demand( pixel_id=good_pixel_id, @@ -65,7 +65,7 @@ class TestChooseTacticalModel: ): """With high demand, the average daily demand is `.>= 25.0`.""" # With 12 time steps per day, the ADD becomes `36.0`. - order_history._data.loc[:, 'n_orders'] = 3 + order_history._data.loc[:, "n_orders"] = 3 result = order_history.choose_tactical_model( pixel_id=good_pixel_id, @@ -83,7 +83,7 @@ class TestChooseTacticalModel: ): """With medium demand, the average daily demand is `>= 10.0` and `< 25.0`.""" # With 12 time steps per day, the ADD becomes `24.0`. - order_history._data.loc[:, 'n_orders'] = 2 + order_history._data.loc[:, "n_orders"] = 2 result = order_history.choose_tactical_model( pixel_id=good_pixel_id, @@ -102,23 +102,23 @@ class TestChooseTacticalModel: """With low demand, the average daily demand is `>= 2.5` and `< 10.0`.""" # With 12 time steps per day, the ADD becomes `12.0` ... data = order_history._data - data.loc[:, 'n_orders'] = 1 + data.loc[:, "n_orders"] = 1 # ... and we set three additional time steps per day to `0`. data.loc[ # all `Pixel`s, all `Order`s in time steps starting at 11 am (slice(None), slice(data.index.levels[1][0], None, 12)), - 'n_orders', + "n_orders", ] = 0 data.loc[ # all `Pixel`s, all `Order`s in time steps starting at 12 am (slice(None), slice(data.index.levels[1][1], None, 12)), - 'n_orders', + "n_orders", ] = 0 data.loc[ # all `Pixel`s, all `Order`s in time steps starting at 1 pm (slice(None), slice(data.index.levels[1][2], None, 12)), - 'n_orders', + "n_orders", ] = 0 result = order_history.choose_tactical_model( @@ -136,7 +136,7 @@ class TestChooseTacticalModel: predict_at, ): """Without demand, the average daily demand is `< 2.5`.""" - order_history._data.loc[:, 'n_orders'] = 0 + order_history._data.loc[:, "n_orders"] = 0 result = order_history.choose_tactical_model( pixel_id=good_pixel_id, @@ -156,7 +156,7 @@ class TestChooseTacticalModel: ... the method raises a `RuntimeError`. """ - with pytest.raises(RuntimeError, match='no rule'): + with pytest.raises(RuntimeError, match="no rule"): order_history.choose_tactical_model( pixel_id=good_pixel_id, predict_day=predict_at.date(), diff --git a/tests/forecasts/timify/test_make_time_series.py b/tests/forecasts/timify/test_make_time_series.py index 2250acf..2d4a105 100644 --- a/tests/forecasts/timify/test_make_time_series.py +++ b/tests/forecasts/timify/test_make_time_series.py @@ -49,7 +49,7 @@ def bad_predict_at(): class TestMakeHorizontalTimeSeries: """Test the `OrderHistory.make_horizontal_ts()` method.""" - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_wrong_pixel(self, order_history, good_predict_at, train_horizon): """A `pixel_id` that is not in the `grid`.""" with pytest.raises(LookupError): @@ -59,7 +59,7 @@ class TestMakeHorizontalTimeSeries: train_horizon=train_horizon, ) - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_time_series_are_series( self, order_history, @@ -77,11 +77,11 @@ class TestMakeHorizontalTimeSeries: training_ts, _, actuals_ts = result assert isinstance(training_ts, pd.Series) - assert training_ts.name == 'n_orders' + assert training_ts.name == "n_orders" assert isinstance(actuals_ts, pd.Series) - assert actuals_ts.name == 'n_orders' + assert actuals_ts.name == "n_orders" - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_time_series_have_correct_length( self, order_history, @@ -104,7 +104,7 @@ class TestMakeHorizontalTimeSeries: assert len(training_ts) == 7 * train_horizon assert len(actuals_ts) == 1 - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_frequency_is_number_of_weekdays( self, order_history, @@ -123,7 +123,7 @@ class TestMakeHorizontalTimeSeries: assert frequency == 7 - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_no_long_enough_history1( self, order_history, @@ -163,7 +163,7 @@ class TestMakeHorizontalTimeSeries: class TestMakeVerticalTimeSeries: """Test the `OrderHistory.make_vertical_ts()` method.""" - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_wrong_pixel(self, order_history, good_predict_at, train_horizon): """A `pixel_id` that is not in the `grid`.""" with pytest.raises(LookupError): @@ -173,7 +173,7 @@ class TestMakeVerticalTimeSeries: train_horizon=train_horizon, ) - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_time_series_are_series( self, order_history, @@ -191,11 +191,11 @@ class TestMakeVerticalTimeSeries: training_ts, _, actuals_ts = result assert isinstance(training_ts, pd.Series) - assert training_ts.name == 'n_orders' + assert training_ts.name == "n_orders" assert isinstance(actuals_ts, pd.Series) - assert actuals_ts.name == 'n_orders' + assert actuals_ts.name == "n_orders" - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_time_series_have_correct_length( self, order_history, @@ -228,7 +228,7 @@ class TestMakeVerticalTimeSeries: assert len(training_ts) == 7 * n_daily_time_steps * train_horizon assert len(actuals_ts) == n_daily_time_steps - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_frequency_is_number_number_of_weekly_time_steps( self, order_history, @@ -253,7 +253,7 @@ class TestMakeVerticalTimeSeries: assert frequency == 7 * n_daily_time_steps - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_no_long_enough_history1( self, order_history, @@ -293,7 +293,7 @@ class TestMakeVerticalTimeSeries: class TestMakeRealTimeTimeSeries: """Test the `OrderHistory.make_realtime_ts()` method.""" - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_wrong_pixel(self, order_history, good_predict_at, train_horizon): """A `pixel_id` that is not in the `grid`.""" with pytest.raises(LookupError): @@ -303,7 +303,7 @@ class TestMakeRealTimeTimeSeries: train_horizon=train_horizon, ) - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_time_series_are_series( self, order_history, @@ -321,11 +321,11 @@ class TestMakeRealTimeTimeSeries: training_ts, _, actuals_ts = result assert isinstance(training_ts, pd.Series) - assert training_ts.name == 'n_orders' + assert training_ts.name == "n_orders" assert isinstance(actuals_ts, pd.Series) - assert actuals_ts.name == 'n_orders' + assert actuals_ts.name == "n_orders" - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_time_series_have_correct_length1( self, order_history, @@ -365,7 +365,7 @@ class TestMakeRealTimeTimeSeries: assert len(training_ts) == 7 * n_daily_time_steps * train_horizon assert len(actuals_ts) == 1 - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_time_series_have_correct_length2( self, order_history, @@ -408,7 +408,7 @@ class TestMakeRealTimeTimeSeries: ) assert len(actuals_ts) == 1 - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_frequency_is_number_number_of_weekly_time_steps( self, order_history, @@ -433,7 +433,7 @@ class TestMakeRealTimeTimeSeries: assert frequency == 7 * n_daily_time_steps - @pytest.mark.parametrize('train_horizon', test_config.TRAIN_HORIZONS) + @pytest.mark.parametrize("train_horizon", test_config.TRAIN_HORIZONS) def test_no_long_enough_history1( self, order_history, diff --git a/tests/forecasts/timify/test_order_history.py b/tests/forecasts/timify/test_order_history.py index d0fb4c5..001dcdc 100644 --- a/tests/forecasts/timify/test_order_history.py +++ b/tests/forecasts/timify/test_order_history.py @@ -19,7 +19,7 @@ class TestSpecialMethods: class TestProperties: """Test the properties in `OrderHistory`.""" - @pytest.mark.parametrize('time_step', test_config.TIME_STEPS) + @pytest.mark.parametrize("time_step", test_config.TIME_STEPS) def test_time_step(self, grid, time_step): """Test `OrderHistory.time_step` property.""" order_history = timify.OrderHistory(grid=grid, time_step=time_step) @@ -50,9 +50,9 @@ class TestProperties: Note: We make `OrderHistory.aggregate_orders()` return a `sentinel` that is cached into `OrderHistory._data`, which must be unset first. """ - monkeypatch.setattr(order_history, '_data', None) + monkeypatch.setattr(order_history, "_data", None) sentinel = object() - monkeypatch.setattr(order_history, 'aggregate_orders', lambda: sentinel) + monkeypatch.setattr(order_history, "aggregate_orders", lambda: sentinel) result1 = order_history.totals result2 = order_history.totals @@ -74,7 +74,7 @@ class TestMethods: """Test `OrderHistory.first_order_at()` with bad input.""" with pytest.raises( LookupError, - match='`pixel_id` is not in the `grid`', + match="`pixel_id` is not in the `grid`", ): order_history.first_order_at(-1) @@ -89,6 +89,6 @@ class TestMethods: """Test `OrderHistory.last_order_at()` with bad input.""" with pytest.raises( LookupError, - match='`pixel_id` is not in the `grid`', + match="`pixel_id` is not in the `grid`", ): order_history.last_order_at(-1) diff --git a/tests/test_config.py b/tests/test_config.py index 072e06a..fcbd5aa 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -7,123 +7,123 @@ import pytest from velofy import configuration -envs = ['production', 'testing'] +envs = ["production", "testing"] -@pytest.mark.parametrize('env', envs) +@pytest.mark.parametrize("env", envs) def test_config_repr(env): """Config objects have the text representation ''.""" config = configuration.make_config(env) - assert str(config) == '' + assert str(config) == "" def test_invalid_config(): """There are only 'production' and 'testing' configurations.""" with pytest.raises(ValueError, match="'production' or 'testing'"): - configuration.make_config('invalid') + configuration.make_config("invalid") -@pytest.mark.parametrize('env', envs) +@pytest.mark.parametrize("env", envs) def test_database_uri_set(env, monkeypatch): """Package does NOT emit warning if DATABASE_URI is set.""" - uri = 'postgresql://user:password@localhost/db' - monkeypatch.setattr(configuration.ProductionConfig, 'DATABASE_URI', uri) - monkeypatch.setattr(configuration.TestingConfig, 'DATABASE_URI', uri) + uri = "postgresql://user:password@localhost/db" + monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) + monkeypatch.setattr(configuration.TestingConfig, "DATABASE_URI", uri) # Prevent that a warning is emitted for a missing R_LIBS_PATH. - monkeypatch.setattr(configuration.Config, 'R_LIBS_PATH', '.cache/r_libs') + monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") with warnings.catch_warnings(record=True) as record: - warnings.simplefilter('always') + warnings.simplefilter("always") configuration.make_config(env) assert len(record) == 0 -@pytest.mark.parametrize('env', envs) +@pytest.mark.parametrize("env", envs) def test_no_database_uri_set_with_testing_env_var(env, monkeypatch): """Package does not work without DATABASE_URI set in the environment.""" - monkeypatch.setattr(configuration.ProductionConfig, 'DATABASE_URI', None) - monkeypatch.setattr(configuration.TestingConfig, 'DATABASE_URI', None) + monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", None) + monkeypatch.setattr(configuration.TestingConfig, "DATABASE_URI", None) - monkeypatch.setenv('TESTING', 'true') + monkeypatch.setenv("TESTING", "true") # Prevent that a warning is emitted for a missing R_LIBS_PATH. - monkeypatch.setattr(configuration.Config, 'R_LIBS_PATH', '.cache/r_libs') + monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") with warnings.catch_warnings(record=True) as record: - warnings.simplefilter('always') + warnings.simplefilter("always") configuration.make_config(env) assert len(record) == 0 -@pytest.mark.parametrize('env', envs) +@pytest.mark.parametrize("env", envs) def test_no_database_uri_set_without_testing_env_var(env, monkeypatch): """Package does not work without DATABASE_URI set in the environment.""" - monkeypatch.setattr(configuration.ProductionConfig, 'DATABASE_URI', None) - monkeypatch.setattr(configuration.TestingConfig, 'DATABASE_URI', None) + monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", None) + monkeypatch.setattr(configuration.TestingConfig, "DATABASE_URI", None) - monkeypatch.delenv('TESTING', raising=False) + monkeypatch.delenv("TESTING", raising=False) # Prevent that a warning is emitted for a missing R_LIBS_PATH. - monkeypatch.setattr(configuration.Config, 'R_LIBS_PATH', '.cache/r_libs') + monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") - with pytest.warns(UserWarning, match='no DATABASE_URI'): + with pytest.warns(UserWarning, match="no DATABASE_URI"): configuration.make_config(env) -@pytest.mark.parametrize('env', envs) +@pytest.mark.parametrize("env", envs) def test_r_libs_path_set(env, monkeypatch): """Package does NOT emit a warning if R_LIBS is set in the environment.""" - monkeypatch.setattr(configuration.Config, 'R_LIBS_PATH', '.cache/r_libs') + monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", ".cache/r_libs") # Prevent that a warning is emitted for a missing DATABASE_URI. - uri = 'postgresql://user:password@localhost/db' - monkeypatch.setattr(configuration.ProductionConfig, 'DATABASE_URI', uri) + uri = "postgresql://user:password@localhost/db" + monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) with warnings.catch_warnings(record=True) as record: - warnings.simplefilter('always') + warnings.simplefilter("always") configuration.make_config(env) assert len(record) == 0 -@pytest.mark.parametrize('env', envs) +@pytest.mark.parametrize("env", envs) def test_no_r_libs_path_set_with_testing_env_var(env, monkeypatch): """Package emits a warning if no R_LIBS is set in the environment ... ... when not testing. """ - monkeypatch.setattr(configuration.Config, 'R_LIBS_PATH', None) - monkeypatch.setenv('TESTING', 'true') + monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", None) + monkeypatch.setenv("TESTING", "true") # Prevent that a warning is emitted for a missing DATABASE_URI. - uri = 'postgresql://user:password@localhost/db' - monkeypatch.setattr(configuration.ProductionConfig, 'DATABASE_URI', uri) + uri = "postgresql://user:password@localhost/db" + monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) with warnings.catch_warnings(record=True) as record: - warnings.simplefilter('always') + warnings.simplefilter("always") configuration.make_config(env) assert len(record) == 0 -@pytest.mark.parametrize('env', envs) +@pytest.mark.parametrize("env", envs) def test_no_r_libs_path_set_without_testing_env_var(env, monkeypatch): """Package emits a warning if no R_LIBS is set in the environment ... ... when not testing. """ - monkeypatch.setattr(configuration.Config, 'R_LIBS_PATH', None) - monkeypatch.delenv('TESTING', raising=False) + monkeypatch.setattr(configuration.Config, "R_LIBS_PATH", None) + monkeypatch.delenv("TESTING", raising=False) # Prevent that a warning is emitted for a missing DATABASE_URI. - uri = 'postgresql://user:password@localhost/db' - monkeypatch.setattr(configuration.ProductionConfig, 'DATABASE_URI', uri) + uri = "postgresql://user:password@localhost/db" + monkeypatch.setattr(configuration.ProductionConfig, "DATABASE_URI", uri) - with pytest.warns(UserWarning, match='no R_LIBS'): + with pytest.warns(UserWarning, match="no R_LIBS"): configuration.make_config(env) @@ -132,5 +132,5 @@ def test_random_testing_schema(): result = configuration.random_schema_name() assert isinstance(result, str) - assert result.startswith('temp_') + assert result.startswith("temp_") assert len(result) == 15 diff --git a/tests/test_version.py b/tests/test_version.py index 9e98a45..bc3fde0 100644 --- a/tests/test_version.py +++ b/tests/test_version.py @@ -46,7 +46,7 @@ class TestSemanticVersioning: """Packaged version follows a strict subset of semantic versioning.""" version_pattern = re.compile( - r'^(0|([1-9]\d*))\.(0|([1-9]\d*))\.(0|([1-9]\d*))(\.dev(0|([1-9]\d*)))?$', + r"^(0|([1-9]\d*))\.(0|([1-9]\d*))\.(0|([1-9]\d*))(\.dev(0|([1-9]\d*)))?$", ) def test_version_is_semantic(self): @@ -58,17 +58,17 @@ class TestSemanticVersioning: # The next two test cases are sanity checks to validate the version_pattern. @pytest.mark.parametrize( - 'version', + "version", [ - '0.1.0', - '1.0.0', - '1.2.3', - '1.23.456', - '123.4.56', - '10.11.12', - '1.2.3.dev0', - '1.2.3.dev1', - '1.2.3.dev10', + "0.1.0", + "1.0.0", + "1.2.3", + "1.23.456", + "123.4.56", + "10.11.12", + "1.2.3.dev0", + "1.2.3.dev1", + "1.2.3.dev10", ], ) def test_valid_semantic_versioning(self, version): @@ -78,27 +78,27 @@ class TestSemanticVersioning: assert result is not None @pytest.mark.parametrize( - 'version', + "version", [ - '1', - '1.2', - '-1.2.3', - '01.2.3', - '1.02.3', - '1.2.03', - '1.2.3.4', - '1.2.3.abc', - '1.2.3-dev0', - '1.2.3+dev0', - '1.2.3.d0', - '1.2.3.develop0', - '1.2.3.dev-1', - '1.2.3.dev01', - '1.2.3..dev0', - '1-2-3', - '1,2,3', - '1..2.3', - '1.2..3', + "1", + "1.2", + "-1.2.3", + "01.2.3", + "1.02.3", + "1.2.03", + "1.2.3.4", + "1.2.3.abc", + "1.2.3-dev0", + "1.2.3+dev0", + "1.2.3.d0", + "1.2.3.develop0", + "1.2.3.dev-1", + "1.2.3.dev01", + "1.2.3..dev0", + "1-2-3", + "1,2,3", + "1..2.3", + "1.2..3", ], ) def test_invalid_semantic_versioning(self, version):