diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..c957f76 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Mechanical commits that `git blame` skips +# => Enable locally with `git config blame.ignoreRevsFile .git-blame-ignore-revs` + +# Use double quotes +ea8f1a13e34bfce01ea66951311e5f5fb5ab967f diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a86b539..12a17a2 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,12 +19,16 @@ repos: - repo: local hooks: + # `require_serial: true` + # => Parallel runs would recreate the same `nox` environment + - id: local-format name: Format the source files entry: uv run nox -s format -- language: unsupported stages: [pre-commit] types: [python] + require_serial: true - id: local-lint name: Lint the source files @@ -32,6 +36,7 @@ repos: language: unsupported stages: [pre-commit] types: [python] + require_serial: true - id: local-test name: Run the test suite @@ -40,6 +45,7 @@ repos: stages: [pre-merge-commit] pass_filenames: false # => No `--` at the end of the "entry" always_run: true + require_serial: true - id: local-doctest name: Run the doctests @@ -48,6 +54,7 @@ repos: stages: [pre-merge-commit] pass_filenames: false # => No `--` at the end of the "entry" always_run: true + require_serial: true # Keep requirements.txt in sync with uv.lock - repo: https://github.com/astral-sh/uv-pre-commit 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 c93f08f..5b090b4 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. @@ -21,9 +21,9 @@ 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 ( # noqa:WPS337 - type_ in {'table', 'column'} - and hasattr(obj, 'schema') # noqa:WPS421 => fix for rare edge case + if ( + type_ in {"table", "column"} + and hasattr(obj, "schema") # => fix for rare edge case and obj.schema != velofy_config.CLEAN_SCHEMA ): return False @@ -33,17 +33,14 @@ def include_object(obj, _name, type_, _reflected, _compare_to): engine = sa.create_engine(velofy_config.DATABASE_URI) +test_schema = f"_{velofy_config.CLEAN_SCHEMA}" if os.getenv("TESTING") else "" + with engine.connect() as connection: context.configure( connection=connection, include_object=include_object, target_metadata=db.Base.metadata, - 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 '' - ), - ), + version_table=f"{velofy_config.ALEMBIC_TABLE}{test_schema}", 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 9d77f3e..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,84 +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.create_table( # noqa:ECE001 - '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')), + 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")), *( - [ # noqa:WPS504 + [ sa.ForeignKeyConstraint( - ['id'], - [f'{config.ORIGINAL_SCHEMA}.cities.id'], - name=op.f('pk_cities_sanity'), - onupdate='RESTRICT', - ondelete='RESTRICT', - ), - ] - if not config.TESTING - else [] - ), - schema=config.CLEAN_SCHEMA, - ) - op.create_table( # noqa:ECE001 - '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'), - ), - sa.CheckConstraint( - '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'), - ), - sa.CheckConstraint( - '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'), - ), - sa.PrimaryKeyConstraint('id', name=op.f('pk_couriers')), - *( - [ # noqa:WPS504 - sa.ForeignKeyConstraint( - ['id'], - [f'{config.ORIGINAL_SCHEMA}.couriers.id'], - name=op.f('pk_couriers_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 @@ -98,63 +53,108 @@ 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')), + "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"), + ), + sa.CheckConstraint( + "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"), + ), + sa.CheckConstraint( + "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"), + ), + 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", + ), + ] + if not config.TESTING + else [] + ), schema=config.CLEAN_SCHEMA, ) - op.create_table( # noqa:ECE001 - '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), + op.create_table( + "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), 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")), *( - [ # noqa:WPS504 + [ 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( # noqa:ECE001 - '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), + 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), 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")), *( - [ # noqa:WPS504 + [ 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( # noqa:ECE001 - '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), + 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), 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")), *( - [ # noqa:WPS504 + [ 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 14ba4ae..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(): @@ -31,7 +31,7 @@ def upgrade(): TO train_horizon; """, - ) # noqa:WPS355 + ) def downgrade(): @@ -45,4 +45,4 @@ def downgrade(): TO training_horizon; """, - ) # noqa:WPS355 + ) 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 a59472f..fd4099d 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(): @@ -29,7 +29,7 @@ def upgrade(): ALTER TABLE {config.CLEAN_SCHEMA}.orders DROP CONSTRAINT ck_orders_on_ordered_timestamps_21; """, - ) # noqa:WPS355 + ) # Add forgotten check constraints to the `orders` table. op.execute( @@ -38,7 +38,7 @@ def upgrade(): ADD CONSTRAINT check_orders_on_ordered_timestamps_placed_at_before_pickup_at CHECK (placed_at < pickup_at); """, - ) # noqa:WPS355 + ) op.execute( f""" ALTER TABLE {config.CLEAN_SCHEMA}.orders @@ -55,92 +55,92 @@ def upgrade(): ) ); """, - ) # noqa:WPS355 + ) # 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=f"ordered_timestamps_{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, ) @@ -403,17 +403,17 @@ def downgrade(): ALTER TABLE {config.CLEAN_SCHEMA}.orders DROP CONSTRAINT check_orders_on_scheduled_orders_must_be_at_quarters_of_an_hour; """, - ) # noqa:WPS355 + ) op.execute( f""" ALTER TABLE {config.CLEAN_SCHEMA}.orders DROP CONSTRAINT check_orders_on_ordered_timestamps_placed_at_before_pickup_at; """, - ) # noqa:WPS355 + ) op.execute( f""" ALTER TABLE {config.CLEAN_SCHEMA}.orders ADD CONSTRAINT ck_orders_on_ordered_timestamps_21 CHECK (cancelled_at > delivery_at); """, - ) # noqa:WPS355 + ) diff --git a/noxfile.py b/noxfile.py index 5889682..36fcb3a 100644 --- a/noxfile.py +++ b/noxfile.py @@ -15,7 +15,7 @@ Further sessions run on demand with `uv run nox -s `: - "deps-lock": Lock dependencies after manual changes in pyproject.toml - "deps-upgrade": Upgrade dependencies within their allowed ranges - "deps-upgrade-check": Show newer versions and the age of all pinned releases -- "init-project": Install the `pre-commit` hooks +- "init-project": Install the `pre-commit` hooks and configure `git blame` - "clean-cwd": Run approx. `git clean -X` with minor exceptions Most sessions accept extra arguments after the "--", @@ -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", # The "./" keeps `bandit` from warning about its module name + "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,14 +180,27 @@ def lint_code(session: Session) -> None: # because they work on the source files directly install_pinned( session, - 'flake8', - 'flake8-annotations', - 'flake8-black', - '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", + "flake8-quotes", + "flake8-sfs", + "flake8-todos", + "flake8-unused-arguments", + "isort", # TODO: See comment on `mypy` below # 'mypy', + "pep8-naming", + "pydoclint[flake8]", ) # Interpret extra arguments as `locations` of source files @@ -195,11 +208,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 @@ -209,7 +222,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`. @@ -222,32 +235,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`. @@ -257,22 +270,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`. @@ -282,21 +295,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') # noqa:WPS421 + 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". @@ -309,24 +322,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`. @@ -341,36 +354,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. @@ -385,12 +398,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. @@ -410,20 +423,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. @@ -438,17 +451,26 @@ 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.""" + """Install the `pre-commit` hooks and configure `git blame`.""" # .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") + + # Skip the commits listed in .git-blame-ignore-revs in `git blame` + session.run( + "git", + "config", + "blame.ignoreRevsFile", + ".git-blame-ignore-revs", + external=True, + ) -@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. @@ -461,19 +483,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 = { @@ -481,12 +503,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]: @@ -514,9 +536,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: @@ -525,38 +547,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, @@ -583,20 +605,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, ) @@ -616,5 +638,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 402c67a..3a2100c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,10 +91,23 @@ dev = [ # Code Analyzers "flake8 (>=7.5.0,<8.0.0)", "flake8-annotations (>=3.3.1,<4.0.0)", + "flake8-bandit (>=4.1.1,<5.0.0)", "flake8-black (>=0.5.0,<0.6.0)", + "flake8-broken-line (>=1.0.0,<2.0.0)", + "flake8-bugbear (>=26.11.22,<27.0.0)", + "flake8-commas (>=4.0.0,<5.0.0)", + "flake8-comprehensions (>=3.17.0,<4.0.0)", + "flake8-debugger (>=4.1.2,<5.0.0)", + "flake8-docstrings (>=1.7.0,<2.0.0)", "flake8-pyproject (>=1.2.4,<2.0.0)", "flake8-pytest-style (>=2.2.0,<3.0.0)", + "flake8-quotes (>=3.4.0,<4.0.0)", + "flake8-sfs (>=1.0.1,<2.0.0)", + "flake8-todos (>=0.3.1,<0.4.0)", + "flake8-unused-arguments (>=0.0.14,<0.1.0)", "mypy (>=2.4.1,<3.0.0)", + "pep8-naming (>=0.15.1,<0.16.0)", + "pydoclint[flake8] (>=0.12.0,<0.13.0)", ] test = [ @@ -134,8 +147,6 @@ target-version = ["py313"] line-length = 88 -skip-string-normalization = true # `wemake-python-styleguide` enforces single quotes - [tool.coverage] @@ -183,15 +194,15 @@ select = [ "E", "W", # pyflakes => basic errors "F4", "F5", "F6", "F7", "F8", "F9", - # ======================== - # wemake-python-styleguide - # Source: https://wemake-python-stylegui.de/en/latest/pages/usage/violations/index.html - # ======================== - "WPS1", "WPS2", "WPS3", "WPS4", "WPS5", "WPS6", - # darglint => docstring matches implementation - "DAR0", "DAR1", "DAR2", "DAR3", "DAR4", "DAR5", + # ======= + # plugins + # ======= + # flake8-annotations => enforce type checking for functions + "ANN0", "ANN2", "ANN3", # flake8-bandit => common security issues "S1", "S2", "S3", "S4", "S5", "S6", "S7", + # flake8-black => complain if black would make changes + "BLK1", "BLK9", # flake8-broken-line => no \ to end a line "N400", # flake8-bugbear => opinionated bugs and design flaws @@ -204,27 +215,20 @@ select = [ "T100", # flake8-docstrings => PEP257 compliance "D1", "D2", "D3", "D4", - # flake8-eradicate => no commented out code - "E800", - # flake8-isort => isort would make changes - "I0", - # flake8-rst-docstrings => valid rst in docstrings - "RST2", "RST3", "RST4", - # flake8-string-format => unify usage of str.format() - "P1", "P2", "P3", - # flake8-quotes => use double quotes everywhere (complying with black) - "Q0", - # pep8-naming - "N8", - # ===== - # other - # ===== - # flake8-annotations => enforce type checking for functions - "ANN0", "ANN2", "ANN3", - # flake8-black => complain if black would make changes - "BLK1", "BLK9", # flake8-pytest-style => enforce a consistent style with pytest "PT0", + # flake8-quotes => use double quotes everywhere (complying with black) + "Q0", + # flake8-sfs => use f-strings as the only type of string formatting + "SFS", + # flake8-todos => unify TODOs + "T00", + # flake8-unused-arguments => declared function arguments must be used + "U100", + # pep8-naming => PEP8 naming conventions + "N8", + # pydoclint => docstring matches implementation + "DOC", ] # By default, flake8 ignores some errors. @@ -234,96 +238,36 @@ ignore = [] # If --ignore is passed on the command # line, still ignore the following: extend-ignore = [ - # TODO: New in `wemake-python-styleguide` v0.15 - v0.17, revisit in the tooling goal - "WPS110", - "WPS237", - "WPS238", - "WPS358", - "WPS456", - "WPS458", - "WPS459", - "WPS462", - "WPS469", # Too long line => duplicate with E501. "B950", + # PEP 257 documents the arguments of `__init__()` in its own docstring. + "DOC301", # Comply with black's style. # Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8 - "E203", "W503", "WPS348", + "E203", "W503", # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`. "PT023", - # Google's Python Style Guide is not reStructuredText - # until after being processed by Sphinx Napoleon. - # Source: https://github.com/peterjc/flake8-rst-docstrings/issues/17 - "RST201", "RST203", "RST210", "RST213", "RST301", - # The "too deep nesting" violation fires off "too early" and cannot be configured. - "WPS220", - # String constant over-use is checked visually by the programmer. - "WPS226", - # Function complexity is checked by `mccabe` (=C901), - # which yields the same result in most cases. - "WPS231", - # Modules as a whole are assumed to be not "too complex". - "WPS232", - # Allow underscores in numbers. - "WPS303", - # f-strings are ok. - "WPS305", - # Classes should not have to specify a base class. - "WPS306", - # Let's be modern: The Walrus is ok. - "WPS332", - # Let's not worry about the number of noqa's. - # Multi-line loops are ok. - "WPS352", - "WPS402", - # Putting logic into __init__.py files may be justified. - "WPS412", - # Allow multiple assignment, e.g., x = y = 123 - "WPS429", - # There are no magic numbers. - "WPS432", + # Allow f-strings as the only type of string formatting. + "SFS301", + # TODOs need neither an author nor an issue. + "T002", "T003", ] per-file-ignores = [ # Top-levels of a sub-packages are intended to import a lot. - "**/__init__.py:F401,WPS201", - # Allow shadowing built-ins and reading __*__ variables. - "docs/conf.py:WPS125,WPS609", + "**/__init__.py:F401", # Type annotations are not strictly enforced. "migrations/env.py:ANN0,ANN2", # - ANN0, ANN2 => Type annotations are not strictly enforced. # - S608 => Do not worry about SQL injection here. - # - WPS114, WPS118 => File names of revisions are ok. - # - WPS204, WPS213 => Revisions may have too many expressions. - "migrations/versions/*.py:ANN0,ANN2,S608,WPS114,WPS118,WPS204,WPS213", - # - ANN0, ANN2 => Type annotations are not strictly enforced. - # - WPS202 => TODO (isort): Check if still too many module members. - # - WPS213 => TODO (isort): Remove after simplifying the nox session "lint". - "noxfile.py:ANN0,ANN2,WPS202,WPS213", - # Allow upper case class variables within classes. - "src/velofy/configuration.py:WPS115", - # The module does not have too many imports. - "src/velofy/db/addresses_addresses.py:WPS201", - # The many noqa's are ok. - "src/velofy/forecasts/models/tactical/horizontal.py:WPS403", - # - S608 => No SQL injection as the inputs come from a safe source. - # - WPS403 => The many noqa's are ok. - "src/velofy/forecasts/timify.py:S608,WPS403", - # - ANN0, ANN2 => Type annotations are not strictly enforced. + "migrations/versions/*.py:ANN0,ANN2,S608", + # Type annotations are not strictly enforced. + "noxfile.py:ANN0,ANN2", + # - ANN0, ANN2, DOC106, DOC107 => Type annotations are not strictly enforced. # - D106 => The `Meta` class inside the factory_boy models do not need a docstring. # - S101 => `assert` statements are ok in the test suite. # - S311 => The `random` module is not used for cryptography. - # - WPS442 => Shadowing outer scopes occurs naturally with mocks. - # - WPS100 => `utils` should be a valid module name. - # - WPS118 => Test names may be longer than 40 characters. - # - WPS202, WPS204, WPS214 => Modules may have many test cases. - # - WPS221 => Do not check for Jones complexity in the test suite. - # - WPS338 => "Private" methods are really just a convention for - # fixtures without a return value. - # - WPS402 => We do not care about the number of "# noqa"s in the test suite. - # - WPS430 => Allow closures. - # - WPS437 => When testing, it is normal to use implementation details. - "tests/*.py:ANN0,ANN2,D106,S101,S311,WPS442,WPS100,WPS118,WPS202,WPS204,WPS214,WPS221,WPS338,WPS402,WPS430,WPS437", + "tests/*.py:ANN0,ANN2,D106,DOC106,DOC107,S101,S311", ] # Explicitly set mccabe's maximum complexity to 10 as recommended by @@ -331,12 +275,6 @@ per-file-ignores = [ # Source: https://en.wikipedia.org/wiki/Cyclomatic_complexity#Limiting_complexity_during_development max-complexity = 10 -# Allow more than wemake-python-styleguide's 5 local variables per function. -max-local-variables = 8 - -# Allow more than wemake-python-styleguide's 7 methods per class. -max-methods = 15 - # Comply with black's style. # Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length max-line-length = 88 @@ -344,24 +282,21 @@ max-line-length = 88 # Preview the code lines that cause errors. show-source = true -# =================================== -# wemake-python-styleguide's settings -# =================================== -allowed-domain-names = [ - "data", - "obj", - "param", - "result", - "results", - "value", -] -max-name-length = 40 -# darglint -strictness = "long" +# pydoclint +style = "google" +arg-type-hints-in-docstring = false +check-return-types = false +check-yield-types = false # flake8-docstrings docstring-convention = "google" -# flake8-eradicate -eradicate-aggressive = true +# flake8-quotes +# Source: https://github.com/zheller/flake8-quotes#configuration +avoid-escape = true +docstring-quotes = "double" +inline-quotes = "double" +multiline-quotes = "double" +# flake8-unused-arguments +unused-arguments-ignore-abstract-functions = true # ============================== # flake8-pytest-style's settings 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 2e4247e..44cf262 100644 --- a/src/velofy/configuration.py +++ b/src/velofy/configuration.py @@ -16,11 +16,9 @@ import warnings def random_schema_name() -> str: """Generate a random PostgreSQL schema name for testing.""" - return 'temp_{name}'.format( - name=''.join( - (random.choice(string.ascii_lowercase) for _ in range(10)), # noqa:S311 - ), - ) + letters = (random.choice(string.ascii_lowercase) for _ in range(10)) # noqa:S311 + name = "".join(letters) + return f"temp_{name}" class Config: @@ -54,33 +52,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 +92,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: @@ -109,12 +107,12 @@ def make_config(env: str = 'production') -> Config: Raises: ValueError: if `env` is not as specified - """ # 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,16 +121,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'): - warnings.warn('Bad configuration: no DATABASE_URI set in the environment') + if config.DATABASE_URI is None and not os.getenv("TESTING"): + warnings.warn( + "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'): - warnings.warn('Bad configuration: no R_LIBS set in the environment') + if config.R_LIBS_PATH is None and not os.getenv("TESTING"): + warnings.warn( + "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 74d3714..7c6fd6d 100644 --- a/src/velofy/console/decorators.py +++ b/src/velofy/console/decorators.py @@ -16,19 +16,19 @@ def db_revision( def decorator(func: Callable[..., Any]) -> Callable[..., Any]: @functools.wraps(func) - def ensure(*args: Any, **kwargs: Any) -> Any: # noqa:WPS430 + 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 91aa0db..6908693 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -19,12 +19,12 @@ 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') -def tactical_heuristic( # noqa:C901,WPS213,WPS216 +@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,DOC001 city: str, side_length: int, time_step: int, @@ -64,13 +64,11 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216 TIME_STEP: length of one time step in minutes; defaults to `60` TRAIN_HORIZON: length of the training horizon; defaults to `8` - """ # noqa:D412,D417,RST215 + """ # noqa:D412,D417 => formatted as `click` help text # Input validation. try: - city_obj = ( - db.session.query(db.City).filter_by(name=city.title()).one() # noqa:WPS221 - ) + city_obj = db.session.query(db.City).filter_by(name=city.title()).one() except orm_exc.NoResultFound: click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"') sys.exit(1) @@ -79,35 +77,35 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216 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. - order_history = timify.OrderHistory(grid=grid, time_step=time_step) # noqa:WPS441 + order_history = timify.OrderHistory(grid=grid, time_step=time_step) order_history.aggregate_orders() # Run the tactical heuristic. - for pixel in grid.pixels: # noqa:WPS441 + for pixel in grid.pixels: # Important: this check may need to be adapted once further # commands are added the make `Forecast`s without the heuristic! # Continue with forecasting on the day the last prediction was made ... last_predict_at = ( - db.session.query(func.max(db.Forecast.start_at)) # noqa:WPS221 + db.session.query(func.max(db.Forecast.start_at)) .join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id) .join(db.Grid, db.Pixel.grid_id == db.Grid.id) .filter(db.Forecast.pixel == pixel) @@ -133,8 +131,8 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216 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 d4673dd..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') # noqa:WPS609 - version = click.style(velofy.__version__, fg='blue') # noqa:WPS609 + 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 4fabcbc..af13c98 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -19,17 +19,17 @@ 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) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) primary_id = sa.Column(sa.Integer, nullable=False, index=True) created_at = sa.Column(sa.DateTime, nullable=False) place_id = sa.Column(sa.Unicode(length=120), nullable=False, index=True) 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,56 +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( - cls=self.__class__.__name__, - street=self.street, - city=self.city_name, - ) + return f"<{self.__class__.__name__}({self.street} in {self.city_name})>" @hybrid.hybrid_property def is_primary(self) -> bool: @@ -116,7 +112,7 @@ class Address(meta.Base): return location @property - def x(self) -> int: # noqa=WPS111 + def x(self) -> int: """The relative x-coordinate within the `.city` in meters. On the implied x-y plane, the `.city`'s southwest corner is the origin. @@ -126,7 +122,7 @@ class Address(meta.Base): return self.location.x @property - def y(self) -> int: # noqa=WPS111 + def y(self) -> int: """The relative y-coordinate within the `.city` in meters. On the implied x-y plane, the `.city`'s southwest corner is the origin. @@ -140,12 +136,12 @@ class Address(meta.Base): Returns: self: enabling method chaining - """ # noqa:D402,DAR203 + """ # noqa:D402 self.city.clear_map() return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `.city.map` object.""" return self.city.map @@ -162,8 +158,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 f7d6791..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 @@ -128,9 +128,7 @@ class Path(meta.Base): # We consider all 2-tuples of `Address`es. The symmetric graph is ... for first, second in itertools.combinations(addresses, 2): # ... implicitly enforced by a precedence constraint for the `.id`s. - first, second = ( # noqa:WPS211 - (first, second) if first.id < second.id else (second, first) - ) + first, second = (first, second) if first.id < second.id else (second, first) # If there is no `Path` object in the database ... path = ( @@ -158,7 +156,7 @@ class Path(meta.Base): paths.append(path) if google_maps: - for path in paths: # noqa:WPS440 + for path in paths: path.sync_with_google_maps() return paths @@ -204,40 +202,40 @@ 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'] # noqa:WPS601 - self.bicycle_duration = route['duration']['value'] # noqa:WPS601 + 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']: - steps.add( # noqa:WPS221 - (step['start_location']['lat'], step['start_location']['lng']), + for step in route["steps"]: + steps.add( + (step["start_location"]["lat"], step["start_location"]["lng"]), ) - steps.add( # noqa:WPS221 - (step['end_location']['lat'], step['end_location']['lng']), + steps.add( + (step["end_location"]["lat"], step["end_location"]["lng"]), ) steps.discard(self.first_address.location.lat_lng) steps.discard(self.second_address.location.lat_lng) - self._directions = json.dumps(list(steps)) # noqa:WPS601 + self._directions = json.dumps(list(steps)) db.session.add(self) db.session.commit() @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Convenience property to obtain the underlying `City.map`.""" return self.first_address.city.map @@ -256,15 +254,15 @@ class Path(meta.Base): return points - def draw( # noqa:WPS211 + def draw( 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 8021b08..b0fdaa5 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -18,10 +18,10 @@ 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( # noqa:WPS125 + id = sa.Column( sa.SmallInteger, primary_key=True, autoincrement=False, @@ -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 f"<{self.__class__.__name__}({self.name})>" @functools.cached_property def center(self) -> utils.Location: @@ -101,7 +101,7 @@ class City(meta.Base): Returns: self: enabling method chaining - """ # noqa:DAR203 note:d334120e + """ # note:d334120e self._map = folium.Map( location=[self.center_latitude, self.center_longitude], zoom_start=self.initial_zoom, @@ -110,12 +110,12 @@ class City(meta.Base): return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """A `folium.Map` object aligned with the city's viewport. See docstring for `.clear_map()` for further info. """ - if not hasattr(self, '_map'): # noqa:WPS421 note:d334120e + if not hasattr(self, "_map"): # note:d334120e self.clear_map() return self._map @@ -137,7 +137,7 @@ class City(meta.Base): db.session.query(db.Address) .filter( db.Address.id.in_( - db.session.query(db.Address.primary_id) # noqa:WPS221 + db.session.query(db.Address.primary_id) .join(db.Restaurant, db.Address.id == db.Restaurant.address_id) .filter(db.Address.city == self) .distinct() @@ -157,10 +157,10 @@ class City(meta.Base): .all() ) if len(restaurants) == 1: - tooltip = f'{restaurants[0].name} (#{restaurants[0].id})' # noqa:WPS221 + tooltip = f"{restaurants[0].name} (#{restaurants[0].id})" else: - tooltip = 'Restaurants ' + ', '.join( # noqa:WPS336 - 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}' # noqa:WPS336 + tooltip += f" | n_orders={n_orders}" address.draw( radius=radius, @@ -239,7 +239,7 @@ class City(meta.Base): if not address.is_primary: continue - marker = folium.Circle( # noqa:WPS317 + marker = folium.Circle( (address.latitude, address.longitude), color=colors[address.zip_code], radius=1, 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 f6dfbe5..ea7f588 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) # noqa:WPS125 + 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,26 @@ 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( - cls=self.__class__.__name__, - courier_id=self.id, - ) + return f"<{self.__class__.__name__}(#{self.id})>" diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index 7afc468..491389e 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -14,36 +14,33 @@ 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) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) def __repr__(self) -> str: """Non-literal text representation.""" - return '<{cls}(#{customer_id})>'.format( - cls=self.__class__.__name__, - customer_id=self.id, - ) + return f"<{self.__class__.__name__}(#{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. Returns: self: enabling method chaining - """ # noqa:D402,DAR203 - self.orders[0].pickup_address.city.clear_map() # noqa:WPS219 + """ # noqa:D402 + self.orders[0].pickup_address.city.clear_map() return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `...city.map` object.""" - return self.orders[0].pickup_address.city.map # noqa:WPS219 + return self.orders[0].pickup_address.city.map - def draw( # noqa:C901,WPS210 + def draw( # noqa:C901 self, restaurants: bool = True, order_counts: bool = False, # pragma: no cover @@ -72,7 +69,7 @@ class Customer(meta.Base): db.Address.id.in_( row.primary_id for row in ( - db.session.query(db.Address.primary_id) # noqa:WPS221 + db.session.query(db.Address.primary_id) .join(db.Order, db.Address.id == db.Order.delivery_address_id) .filter(db.Order.customer_id == self.id) .distinct() @@ -108,7 +105,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: @@ -122,7 +119,7 @@ class Customer(meta.Base): db.session.query(db.Address) .filter( db.Address.id.in_( - db.session.query(db.Address.primary_id) # noqa:WPS221 + db.session.query(db.Address.primary_id) .join(db.Order, db.Address.id == db.Order.pickup_address_id) .filter(db.Order.customer_id == self.id) .distinct() @@ -132,23 +129,23 @@ class Customer(meta.Base): .all() ) - for address in pickup_addresses: # noqa:WPS440 + for address in pickup_addresses: # Show the restaurant's name if there is only one. # Otherwise, list all the restaurants' ID's. # We cannot show the `Order.restaurant.name` due to the aggregation. restaurants = ( db.session.query(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) - .filter(db.Address.primary_id == address.id) # noqa:WPS441 + .filter(db.Address.primary_id == address.id) .all() ) 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( # noqa:WPS336 - f'#{restaurant.id}' for restaurant in restaurants # type:ignore + tooltip = "Restaurants " + ", ".join( + f"#{restaurant.id}" for restaurant in restaurants # type:ignore ) if order_counts: @@ -156,7 +153,7 @@ class Customer(meta.Base): db.session.query(db.Order) .join(db.Address, db.Order.pickup_address_id == db.Address.id) .filter(db.Order.customer_id == self.id) - .filter(db.Address.primary_id == address.id) # noqa:WPS441 + .filter(db.Address.primary_id == address.id) .count() ) if n_orders >= 25: @@ -170,9 +167,9 @@ class Customer(meta.Base): else: radius = 1 - tooltip += f' | n_orders={n_orders}' # noqa:WPS336 + tooltip += f" | n_orders={n_orders}" - address.draw( # noqa:WPS441 + address.draw( radius=radius, color=config.RESTAURANT_COLOR, fill_color=config.RESTAURANT_COLOR, @@ -181,7 +178,7 @@ class Customer(meta.Base): ) else: - address.draw( # noqa:WPS441 + address.draw( radius=1, color=config.RESTAURANT_COLOR, tooltip=tooltip, diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index 8f28899..1296978 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -20,10 +20,10 @@ 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) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) pixel_id = sa.Column(sa.Integer, nullable=False, index=True) start_at = sa.Column(sa.DateTime, nullable=False) time_step = sa.Column(sa.SmallInteger, nullable=False) @@ -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,33 +125,29 @@ 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( - cls=self.__class__.__name__, - prediction=self.prediction, - n_x=self.pixel.n_x, - n_y=self.pixel.n_y, - start_at=self.start_at, - ) + cls = self.__class__.__name__ + pixel = f"({self.pixel.n_x}|{self.pixel.n_y})" + return f"<{cls}: {self.prediction} for pixel {pixel} at {self.start_at}>" @classmethod - def from_dataframe( # noqa:WPS210,WPS211 + def from_dataframe( cls, pixel: db.Pixel, time_step: int, @@ -182,21 +178,21 @@ class Forecast(meta.Base): Returns: forecasts: the `data` as `Forecast` objects - """ # noqa:RST215 + """ forecasts = [] 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 a77d4a2..f035174 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -19,10 +19,10 @@ class Grid(meta.Base): That is configures via the `Grid.side_length` attribute. """ - __tablename__ = 'grids' + __tablename__ = "grids" # Columns - id = sa.Column( # noqa:WPS125 + id = sa.Column( sa.SmallInteger, primary_key=True, autoincrement=True, @@ -33,28 +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( - cls=self.__class__.__name__, - area=self.pixel_area, - ) + return f"<{self.__class__.__name__}: {self.pixel_area} sqr. km>" # Convenience properties @property @@ -63,7 +60,7 @@ class Grid(meta.Base): return round((self.side_length**2) / 1_000_000, 1) @classmethod - def gridify(cls, city: db.City, side_length: int) -> db.Grid: # noqa:WPS210 + def gridify(cls, city: db.City, side_length: int) -> db.Grid: """Create a fully populated `Grid` for a `city`. The `Grid` contains only `Pixel`s that have at least one @@ -119,12 +116,12 @@ class Grid(meta.Base): Returns: self: enabling method chaining - """ # noqa:D402,DAR203 + """ # noqa:D402 self.city.clear_map() return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `.city.map` object.""" return self.city.map diff --git a/src/velofy/db/meta.py b/src/velofy/db/meta.py index a9ddef1..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', # noqa:WPS323 - 'fk': 'fk_%(table_name)s_to_%(referred_table_name)s_via_%(column_0_N_name)s', # noqa:E501,WPS323 - 'uq': 'uq_%(table_name)s_on_%(column_0_N_name)s', # noqa:WPS323 - 'ix': 'ix_%(table_name)s_on_%(column_0_N_name)s', # noqa:WPS323 - 'ck': 'ck_%(table_name)s_on_%(constraint_name)s', # noqa:WPS323 + "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 f12bfa7..cf198ff 100644 --- a/src/velofy/db/orders.py +++ b/src/velofy/db/orders.py @@ -12,14 +12,14 @@ from velofy import db from velofy.db import meta -class Order(meta.Base): # noqa:WPS214 +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) # noqa:WPS125 - _delivery_id = sa.Column('delivery_id', sa.Integer, index=True, unique=True) + id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) + _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): # noqa:WPS214 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): # noqa:WPS214 # 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): # noqa:WPS214 ) ) """, - name='ad_hoc_orders_within_business_hours', + name="ad_hoc_orders_within_business_hours", ), sa.CheckConstraint( """ @@ -153,7 +153,7 @@ class Order(meta.Base): # noqa:WPS214 ) ) """, - name='scheduled_orders_within_business_hours', + name="scheduled_orders_within_business_hours", ), sa.CheckConstraint( """ @@ -167,7 +167,7 @@ class Order(meta.Base): # noqa:WPS214 = 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): # noqa:WPS214 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): # noqa:WPS214 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): # noqa:WPS214 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): # noqa:WPS214 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): # noqa:WPS214 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): # noqa:WPS214 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=f"ordered_timestamps_{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 @@ -364,7 +364,7 @@ class Order(meta.Base): # noqa:WPS214 def corrected(self) -> bool: """If any timestamp was corrected as compared to the original data.""" return ( - self.scheduled_delivery_at_corrected # noqa:WPS222 => too much logic + self.scheduled_delivery_at_corrected # => too much logic or self.cancelled_at_corrected or self.restaurant_notified_at_corrected or self.restaurant_confirmed_at_corrected @@ -385,9 +385,9 @@ class Order(meta.Base): # noqa:WPS214 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): # noqa:WPS214 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): # noqa:WPS214 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): # noqa:WPS214 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,26 +534,23 @@ class Order(meta.Base): # noqa:WPS214 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( - cls=self.__class__.__name__, - order_id=self.id, - ) + return f"<{self.__class__.__name__}(#{self.id})>" def draw(self) -> folium.Map: # pragma: no cover """Draw the `.waypoints` from `.pickup_address` to `.delivery_address`. @@ -566,8 +563,8 @@ class Order(meta.Base): # noqa:WPS214 """ 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 a4a80ba..4eee7f1 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -25,10 +25,10 @@ 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) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) grid_id = sa.Column(sa.SmallInteger, nullable=False, index=True) n_x = sa.Column(sa.SmallInteger, nullable=False, index=True) n_y = sa.Column(sa.SmallInteger, nullable=False, index=True) @@ -36,31 +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( - cls=self.__class__.__name__, - x=self.n_x, - y=self.n_y, - ) + return f"<{self.__class__.__name__}: ({self.n_x}|{self.n_y})>" # Convenience properties @@ -136,16 +132,16 @@ class Pixel(meta.Base): Returns: self: enabling method chaining - """ # noqa:D402,DAR203 + """ # noqa:D402 self.grid.city.clear_map() return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `.city.map` object.""" return self.grid.city.map - def draw( # noqa:C901,WPS210 + def draw( # noqa:C901 self, restaurants: bool = True, order_counts: bool = False, # pragma: no cover @@ -163,17 +159,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 +216,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( # noqa:WPS336 - 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 +243,7 @@ class Pixel(meta.Base): else: radius = 1 - tooltip += f' | n_orders={n_orders}' # noqa:WPS336 + 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..001d7ab 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,82 +266,79 @@ class ReplayedOrder(meta.Base): # and the non-simulated columns removed. sa.CheckConstraint( constraint, - name='ordered_timestamps_{index}'.format(index=index), + name=f"ordered_timestamps_{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( - cls=self.__class__.__name__, - order_id=self.actual.id, - ) + return f"<{self.__class__.__name__}(#{self.actual.id})>" # Convenience properties diff --git a/src/velofy/db/replay/simulations.py b/src/velofy/db/replay/simulations.py index 88e3547..798a69c 100644 --- a/src/velofy/db/replay/simulations.py +++ b/src/velofy/db/replay/simulations.py @@ -12,10 +12,10 @@ 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) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) city_id = sa.Column(sa.SmallInteger, nullable=False, index=True) strategy = sa.Column(sa.Unicode(length=100), nullable=False, index=True) # `.run` may be used as random seed. @@ -24,25 +24,21 @@ 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( - cls=self.__class__.__name__, - strategy=self.strategy, - run=self.run, - city=self.city.name, - ) + cls = self.__class__.__name__ + return f"<{cls}({self.strategy} #{self.run} in {self.city.name})>" diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 181b5ac..50a0cce 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -19,10 +19,10 @@ class Restaurant(meta.Base): which in most cases is also the only one. """ - __tablename__ = 'restaurants' + __tablename__ = "restaurants" # Columns - id = sa.Column( # noqa:WPS125 + id = sa.Column( sa.SmallInteger, primary_key=True, autoincrement=False, @@ -35,42 +35,42 @@ 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 f"<{self.__class__.__name__}({self.name})>" def clear_map(self) -> Restaurant: # pragma: no cover """Shortcut to the `.address.city.clear_map()` method. Returns: self: enabling method chaining - """ # noqa:D402,DAR203 + """ # noqa:D402 self.address.city.clear_map() return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `.address.city.map` object.""" return self.address.city.map @@ -100,7 +100,7 @@ class Restaurant(meta.Base): db.Address.id.in_( row.primary_id for row in ( - db.session.query(db.Address.primary_id) # noqa:WPS221 + db.session.query(db.Address.primary_id) .join( db.Order, db.Address.id == db.Order.delivery_address_id, @@ -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 02edaec..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}' # noqa:WPS221 + 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 a90fc97..21b4eef 100644 --- a/src/velofy/db/utils/locations.py +++ b/src/velofy/db/utils/locations.py @@ -7,7 +7,7 @@ from typing import Optional, Tuple import utm -class Location: # noqa:WPS214 +class Location: """A location represented in WGS84 and UTM coordinates. WGS84: @@ -46,11 +46,14 @@ class Location: # noqa:WPS214 Convention is {ZONE} {EASTING} {NORTHING}. + Returns: + text representation in the UTM system + Example: >>> Location(43.6532, -79.3832) """ - return f'' # noqa:WPS221 + return f"" @property def latitude(self) -> float: @@ -86,7 +89,7 @@ class Location: # noqa:WPS214 @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,29 +102,29 @@ class Location: # noqa:WPS214 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) @property - def x(self) -> int: # noqa:WPS111 + def x(self) -> int: """The `.easting` of the location in meters, relative to some origin. 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 @property - def y(self) -> int: # noqa:WPS111 + def y(self) -> int: """The `.northing` of the location in meters, relative to some origin. 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 +139,13 @@ class Location: # noqa:WPS214 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 337527d..7aa88f6 100644 --- a/src/velofy/forecasts/methods/arima.py +++ b/src/velofy/forecasts/methods/arima.py @@ -33,21 +33,21 @@ def predict( """ # Initialize R only if it is actually used. # For example, the nox session "ci-tests-fast" does not use it. - from velofy import init_r # noqa:F401,WPS433 + 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 36482af..3104667 100644 --- a/src/velofy/forecasts/methods/decomposition.py +++ b/src/velofy/forecasts/methods/decomposition.py @@ -12,7 +12,7 @@ from rpy2 import robjects from rpy2.robjects import pandas2ri -def stl( # noqa:C901,WPS210,WPS211 +def stl( # noqa:C901 time_series: pd.Series, *, frequency: int, @@ -26,7 +26,7 @@ def stl( # noqa:C901,WPS210,WPS211 jt: Optional[int] = None, jl: Optional[int] = None, ni: int = 2, - no: int = 0, # noqa:WPS110 + no: int = 0, ) -> pd.DataFrame: """Decompose a time series into seasonal, trend, and residual components. @@ -95,17 +95,17 @@ def stl( # noqa:C901,WPS210,WPS211 # 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)]`, " + + f"which is {default_nt}", ) else: nt = default_nt @@ -114,42 +114,42 @@ def stl( # noqa:C901,WPS210,WPS211 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: @@ -157,14 +157,14 @@ def stl( # noqa:C901,WPS210,WPS211 # Initialize R only if it is actually used. # For example, the nox session "ci-tests-fast" does not use it. - from velofy import init_r # noqa:F401,WPS433 + 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, @@ -177,16 +177,16 @@ def stl( # noqa:C901,WPS210,WPS211 jl, robust, ni, - no, # noqa:WPS221 + no, ) # Unpack the result to a `pd.DataFrame`. 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 6962f6f..39c443a 100644 --- a/src/velofy/forecasts/methods/ets.py +++ b/src/velofy/forecasts/methods/ets.py @@ -34,21 +34,21 @@ def predict( """ # Initialize R only if it is actually used. # For example, the nox session "ci-tests-fast" does not use it. - from velofy import init_r # noqa:F401,WPS433 + 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. @@ -56,7 +56,7 @@ def predict( f""" as.data.frame( forecast( - ets(data, model = "{model:s}"), + ets(data, model = "{model:s}"), # noqa:B907 h = {n_steps_ahead:d} ) ) @@ -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/__init__.py b/src/velofy/forecasts/models/__init__.py index 5395e1d..17b16b2 100644 --- a/src/velofy/forecasts/models/__init__.py +++ b/src/velofy/forecasts/models/__init__.py @@ -27,7 +27,7 @@ predictive routing strategy employed by the UDP. A future `planning` sub-package will contain the `*Model`s used to plan the `Courier`'s shifts a week ahead. -""" # noqa:RST215 +""" from velofy.forecasts.models.base import ForecastingModelABC from velofy.forecasts.models.tactical.horizontal import HorizontalETSModel diff --git a/src/velofy/forecasts/models/base.py b/src/velofy/forecasts/models/base.py index 7f98bf6..2b60b85 100644 --- a/src/velofy/forecasts/models/base.py +++ b/src/velofy/forecasts/models/base.py @@ -52,7 +52,7 @@ class ForecastingModelABC(abc.ABC): actuals, predictions, and possibly 80%/95% confidence intervals; includes a row for the time step starting at `predict_at` and may contain further rows for other time steps on the same day - """ # noqa:DAR202 + """ def make_forecast( self, @@ -78,10 +78,11 @@ class ForecastingModelABC(abc.ABC): actual, prediction, and possibly 80%/95% confidence intervals for the time step starting at `predict_at` - # noqa:DAR401 RuntimeError + Raises: + RuntimeError: `*Model.predict()` misses the prediction for `predict_at` """ - if ( # noqa:WPS337 - cached_forecast := db.session.query(db.Forecast) # noqa:WPS221 + if ( + cached_forecast := db.session.query(db.Forecast) .filter_by(pixel=pixel) .filter_by(start_at=predict_at) .filter_by(time_step=self._order_history.time_step) @@ -118,5 +119,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/__init__.py b/src/velofy/forecasts/models/tactical/__init__.py index f71038c..1652a4d 100644 --- a/src/velofy/forecasts/models/tactical/__init__.py +++ b/src/velofy/forecasts/models/tactical/__init__.py @@ -13,4 +13,4 @@ Urban Delivery Platform". For the paper check: https://code.webartifex.de/alexander/velofy-forecasting/src/branch/main/paper.pdf https://www.sciencedirect.com/science/article/pii/S1366554520307936 -""" # noqa:RST215 +""" diff --git a/src/velofy/forecasts/models/tactical/horizontal.py b/src/velofy/forecasts/models/tactical/horizontal.py index 9a4ab81..6a08143 100644 --- a/src/velofy/forecasts/models/tactical/horizontal.py +++ b/src/velofy/forecasts/models/tactical/horizontal.py @@ -5,7 +5,7 @@ corresponding to the same time of day as the one to be predicted (i.e., the one starting at `predict_at`). Then, they make a prediction for only one day into the future. Thus, the training time series have a `frequency` of `7`, the number of days in a week. -""" # noqa:RST215 +""" import datetime as dt @@ -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, @@ -40,7 +40,8 @@ class HorizontalETSModel(base.ForecastingModelABC): confidence intervals (i.e, the four "low/high/80/95" columns); contains one row for the `predict_at` time step - # noqa:DAR401 RuntimeError + Raises: + RuntimeError: an internal consistency check fails """ # Generate the historic (and horizontal) order time series. training_ts, frequency, actuals_ts = self._order_history.make_horizontal_ts( @@ -51,7 +52,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 +62,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 +76,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, @@ -96,7 +97,8 @@ class HorizontalSMAModel(base.ForecastingModelABC): this model does not support confidence intervals; contains one row for the `predict_at` time step - # noqa:DAR401 RuntimeError + Raises: + RuntimeError: an internal consistency check fails """ # Generate the historic (and horizontal) order time series. training_ts, frequency, actuals_ts = self._order_history.make_horizontal_ts( @@ -107,10 +109,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 +120,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 ( # noqa:WPS337 - predictions[['actual', 'prediction']].isnull().any().any() + if ( + 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 d9c9901..f515365 100644 --- a/src/velofy/forecasts/models/tactical/other.py +++ b/src/velofy/forecasts/models/tactical/other.py @@ -2,7 +2,7 @@ ... that cannot be classified into either "horizontal", "vertical", or "real-time". -""" # noqa:RST215 +""" import datetime as dt @@ -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, @@ -40,7 +40,8 @@ class TrivialModel(base.ForecastingModelABC): this model does not support confidence intervals; contains one row for the `predict_at` time step - # noqa:DAR401 RuntimeError + Raises: + RuntimeError: an internal consistency check fails """ # Generate the historic order time series mainly to check if a valid # `training_ts` exists (i.e., the demand history is long enough). @@ -52,29 +53,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 78933e8..e1399e6 100644 --- a/src/velofy/forecasts/models/tactical/realtime.py +++ b/src/velofy/forecasts/models/tactical/realtime.py @@ -7,7 +7,7 @@ the one starting at `predict_at`). Thus, the training time series have a day. For example, for 60-minute time steps, the `frequency` becomes `7 * 12` (= operating hours from 11 am to 11 pm), which is `84`. Real-time `*Model`s train the forecasting `methods` on a seasonally decomposed time series internally. -""" # noqa:RST215 +""" import datetime as dt @@ -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, @@ -42,7 +42,8 @@ class RealtimeARIMAModel(base.ForecastingModelABC): confidence intervals (i.e, the four "low/high/80/95" columns); contains one row for the `predict_at` time step - # noqa:DAR401 RuntimeError + Raises: + RuntimeError: an internal consistency check fails """ # Generate the historic (and real-time) order time series. training_ts, frequency, actuals_ts = self._order_history.make_realtime_ts( @@ -63,7 +64,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 +72,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 +87,26 @@ class RealtimeARIMAModel(base.ForecastingModelABC): # the extrapolated seasonal component. predictions = pd.DataFrame( data={ - 'actual': actuals_ts, - 'prediction': ( - seasonal_predictions['prediction'] # noqa:WPS204 - + 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 +114,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 3ac44d7..d41da24 100644 --- a/src/velofy/forecasts/models/tactical/vertical.py +++ b/src/velofy/forecasts/models/tactical/vertical.py @@ -7,7 +7,7 @@ Thus, the training time series have a `frequency` of the number of weekdays, steps, the `frequency` becomes `7 * 12` (= operating hours from 11 am to 11 pm), which is `84`. Vertical `*Model`s train the forecasting `methods` on a seasonally decomposed time series internally. -""" # noqa:RST215 +""" import datetime as dt @@ -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, @@ -42,7 +42,8 @@ class VerticalARIMAModel(base.ForecastingModelABC): confidence intervals (i.e, the four "low/high/80/95" columns); contains several rows, including one for the `predict_at` time step - # noqa:DAR401 RuntimeError + Raises: + RuntimeError: an internal consistency check fails """ # Generate the historic (and vertical) order time series. training_ts, frequency, actuals_ts = self._order_history.make_vertical_ts( @@ -63,7 +64,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 +72,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 +87,26 @@ class VerticalARIMAModel(base.ForecastingModelABC): # the extrapolated seasonal component. predictions = pd.DataFrame( data={ - 'actual': actuals_ts, - 'prediction': ( - seasonal_predictions['prediction'] # noqa:WPS204 - + 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 +114,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 bfc3a3f..24b50e9 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -27,7 +27,8 @@ class OrderHistory: grid: pixel grid used to aggregate orders spatially time_step: interval length (in minutes) into which orders are aggregated - # noqa:DAR401 RuntimeError + Raises: + RuntimeError: the configuration has invalid `TIME_STEPS` """ self._grid = grid self._time_step = time_step @@ -37,7 +38,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()`. @@ -70,7 +71,7 @@ class OrderHistory: # This happens when there is no demand in the `Pixel` in the given `time_step`. data = pd.read_sql_query( sa.text( - f""" -- # noqa:WPS221 + f""" -- # noqa:S608 SELECT pixel_id, start_at, @@ -139,9 +140,9 @@ class OrderHistory: pixel_id, start_at; """, - ), # noqa:WPS355 + ), con=db.connection, - index_col=['pixel_id', 'start_at'], + index_col=["pixel_id", "start_at"], ) if data.empty: @@ -162,13 +163,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) @@ -183,19 +184,18 @@ class OrderHistory: Raises: LookupError: `pixel_id` not in `grid` - - # noqa:DAR401 RuntimeError + RuntimeError: no orders in the pixel """ 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( @@ -217,19 +217,18 @@ class OrderHistory: Raises: LookupError: `pixel_id` not in `grid` - - # noqa:DAR401 RuntimeError + RuntimeError: no orders in the pixel """ 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( @@ -240,7 +239,7 @@ class OrderHistory: last_order.minute, ) - def make_horizontal_ts( # noqa:WPS210 + def make_horizontal_ts( self, pixel_id: int, predict_at: dt.datetime, @@ -270,10 +269,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,18 +300,18 @@ 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 - def make_vertical_ts( # noqa:WPS210 + def make_vertical_ts( self, pixel_id: int, predict_day: dt.date, @@ -342,10 +341,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 +371,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,14 +393,14 @@ 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 - def make_realtime_ts( # noqa:WPS210 + def make_realtime_ts( self, pixel_id: int, predict_at: dt.datetime, @@ -431,10 +430,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 +471,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 +488,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 @@ -524,7 +523,7 @@ class OrderHistory: Returns: average number of orders per day """ - training_ts, _, _ = self.make_vertical_ts( # noqa:WPS434 + training_ts, _, _ = self.make_vertical_ts( pixel_id=pixel_id, predict_day=predict_day, train_horizon=train_horizon, @@ -565,8 +564,9 @@ class OrderHistory: Returns: most promising forecasting `*Model` - # noqa:DAR401 RuntimeError - """ # noqa:RST215 + Raises: + RuntimeError: no rule for the average daily demand and training horizon + """ add = self.avg_daily_demand( pixel_id=pixel_id, predict_day=predict_day, @@ -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 9afc8c6..29b1106 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -13,15 +13,15 @@ from rpy2.robjects import packages as rpackages # Suppress R's messages to stdout and stderr. # Source: https://stackoverflow.com/a/63220287 -rcallbacks.consolewrite_print = lambda msg: None # pragma: no cover -rcallbacks.consolewrite_warnerror = lambda msg: None # pragma: no cover +rcallbacks.consolewrite_print = lambda _msg: None # pragma: no cover +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: # noqa:WPS229 - rpackages.importr('forecast') - rpackages.importr('zoo') +try: + 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 762a670..660edb1 100644 --- a/tests/console/test_gridify.py +++ b/tests/console/test_gridify.py @@ -8,7 +8,7 @@ from velofy.console import gridify @pytest.mark.db -def test_two_pixels_with_two_addresses( # noqa:WPS211 +def test_two_pixels_with_two_addresses( cli, db_session, monkeypatch, @@ -44,7 +44,7 @@ def test_two_pixels_with_two_addresses( # noqa:WPS211 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 3dde8e2..b519e46 100644 --- a/tests/db/fake_data/factories/addresses.py +++ b/tests/db/fake_data/factories/addresses.py @@ -15,9 +15,9 @@ 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) # noqa:WPS125 + id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) # When testing, all addresses are considered primary ones. @@ -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 d45bde0..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) # noqa:WPS125 + 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 cbef0a5..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) # noqa:WPS125 + 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 5052587..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. @@ -41,7 +41,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): # Timestamps after `cancelled_at` are discarded # by the `post_generation` hook at the end of the `OrderFactory`. - cancel_ = factory.Trait( # noqa:WPS120 -> leading underscore does not work + cancel_ = factory.Trait( # -> leading underscore does not work cancelled=True, cancelled_at_corrected=False, ) @@ -65,7 +65,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): ) # Generic attributes - id = factory.Sequence(lambda num: num) # noqa:WPS125 + id = factory.Sequence(lambda num: num) # customer -> set by the `make_order` fixture for better control # Attributes regarding the specialization of an `Order`: ad-hoc or scheduled. @@ -182,12 +182,12 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): # Statistical attributes -> calculate realistic stats logged_delivery_distance = factory.LazyAttribute( - lambda obj: distance.great_circle( # noqa:WPS317 + lambda obj: distance.great_circle( (obj.pickup_address.latitude, obj.pickup_address.longitude), (obj.delivery_address.latitude, obj.delivery_address.longitude), ).meters, ) - logged_avg_speed = factory.LazyAttribute( # noqa:ECE001 + logged_avg_speed = factory.LazyAttribute( lambda obj: round( ( obj.logged_avg_speed_distance 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 90de785..c000a6f 100644 --- a/tests/db/fake_data/factories/restaurants.py +++ b/tests/db/fake_data/factories/restaurants.py @@ -16,9 +16,9 @@ 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) # noqa:WPS125 + id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) name = factory.LazyFunction( lambda: f"{_restaurant_names.first_name()}'s Restaurant", diff --git a/tests/db/fake_data/factories/utils.py b/tests/db/fake_data/factories/utils.py index 367d49f..9eb1f41 100644 --- a/tests/db/fake_data/factories/utils.py +++ b/tests/db/fake_data/factories/utils.py @@ -6,7 +6,7 @@ import random from tests import config as test_config -def random_timespan( # noqa:WPS211 +def random_timespan( *, min_hours=0, min_minutes=0, @@ -19,7 +19,10 @@ def random_timespan( # noqa:WPS211 total_min_seconds = min_hours * 3600 + min_minutes * 60 + min_seconds total_max_seconds = max_hours * 3600 + max_minutes * 60 + max_seconds return dt.timedelta( - seconds=random.randint(int(total_min_seconds), int(total_max_seconds)) + seconds=random.randint( + int(total_min_seconds), + int(total_max_seconds), + ), ) diff --git a/tests/db/fake_data/fixture_makers.py b/tests/db/fake_data/fixture_makers.py index ffe6a3b..570e63c 100644 --- a/tests/db/fake_data/fixture_makers.py +++ b/tests/db/fake_data/fixture_makers.py @@ -78,7 +78,7 @@ def make_order(make_address, make_courier, make_customer, make_restaurant): scheduled: if an `Order` is a pre-order restaurant: who receives the `Order`; defaults to a new `Restaurant` courier: who delivered the `Order`; defaults to a new `Courier` - kwargs: additional keyword arguments forwarded to the `OrderFactory` + **kwargs: additional keyword arguments forwarded to the `OrderFactory` Returns: order @@ -119,7 +119,7 @@ def make_replay_order(make_order, simulation): Args: scheduled: if an `Order` is a pre-order order: the `Order` that is replayed - kwargs: keyword arguments forwarded to the `ReplayedOrderFactory` + **kwargs: keyword arguments forwarded to the `ReplayedOrderFactory` Returns: order @@ -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 2ae15df..e4fdb6d 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -21,7 +21,7 @@ def another_address(make_address): @pytest.fixture def path(address, another_address, make_address): """A `Path` from `address` to `another_address`.""" - air_distance = distance.great_circle( # noqa:WPS317 + air_distance = distance.great_circle( address.location.lat_lng, another_address.location.lat_lng, ).meters @@ -31,7 +31,7 @@ def path(address, another_address, make_address): directions = json.dumps( [ (float(add.latitude), float(add.longitude)) - for add in (make_address() for _ in range(5)) # noqa:WPS335 + for add in (make_address() for _ in range(5)) ], ) @@ -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,12 +192,13 @@ class TestConstraints: with pytest.raises( sa_exc.IntegrityError, - match='realistic_bicycle_travel_time', + match="realistic_bicycle_travel_time", ): db_session.commit() @pytest.mark.db +@pytest.mark.usefixtures("_prepare_db") class TestFromAddresses: """Test the alternative constructor `Path.from_addresses()`. @@ -214,7 +215,6 @@ class TestFromAddresses: """ db_session.add(address) - @pytest.mark.usefixtures('_prepare_db') def test_make_path_instance( self, db_session, @@ -228,7 +228,6 @@ class TestFromAddresses: assert db_session.query(db.Path).count() == 1 - @pytest.mark.usefixtures('_prepare_db') def test_make_the_same_path_instance_twice( self, db_session, @@ -246,17 +245,14 @@ class TestFromAddresses: assert db_session.query(db.Path).count() == 1 - @pytest.mark.usefixtures('_prepare_db') - def test_structure_of_return_value(self, db_session, address, another_address): + def test_structure_of_return_value(self, 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') def test_instances_must_have_air_distance( self, - db_session, address, another_address, ): @@ -267,10 +263,8 @@ class TestFromAddresses: assert result.air_distance is not None - @pytest.mark.usefixtures('_prepare_db') def test_do_not_sync_instances_with_google_maps( self, - db_session, address, another_address, ): @@ -282,10 +276,8 @@ class TestFromAddresses: assert result.bicycle_distance is None assert result.bicycle_duration is None - @pytest.mark.usefixtures('_prepare_db') def test_sync_instances_with_google_maps( self, - db_session, address, another_address, monkeypatch, @@ -296,7 +288,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,22 +297,19 @@ class TestFromAddresses: assert result.bicycle_distance is not None assert result.bicycle_duration is not None - @pytest.mark.usefixtures('_prepare_db') - def test_one_path_for_two_addresses(self, db_session, address, another_address): + def test_one_path_for_two_addresses(self, 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') - def test_two_paths_for_three_addresses(self, db_session, make_address): + def test_two_paths_for_three_addresses(self, 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') - def test_six_paths_for_four_addresses(self, db_session, make_address): + def test_six_paths_for_four_addresses(self, make_address): """Test instantiation of a new `Path` instance.""" result = len(db.Path.from_addresses(*[make_address() for _ in range(4)])) @@ -328,7 +317,6 @@ class TestFromAddresses: # Tests for the `Path.from_order()` convenience method. - @pytest.mark.usefixtures('_prepare_db') def test_make_path_instance_from_order( self, db_session, @@ -341,7 +329,6 @@ class TestFromAddresses: assert db_session.query(db.Path).count() == 1 - @pytest.mark.usefixtures('_prepare_db') def test_make_the_same_path_instance_from_order_twice( self, db_session, @@ -358,17 +345,14 @@ class TestFromAddresses: assert db_session.query(db.Path).count() == 1 - @pytest.mark.usefixtures('_prepare_db') - def test_structure_of_return_value_from_order(self, db_session, order): + def test_structure_of_return_value_from_order(self, order): """Test instantiation of a new `Path` instance.""" result = db.Path.from_order(order) assert isinstance(result, db.Path) - @pytest.mark.usefixtures('_prepare_db') def test_sync_instance_from_order_with_google_maps( self, - db_session, order, monkeypatch, ): @@ -378,7 +362,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) @@ -387,259 +371,260 @@ class TestFromAddresses: @pytest.mark.db +@pytest.mark.usefixtures("_fake_google_api", "db_session") class TestSyncWithGoogleMaps: """Test the `Path.sync_with_google_maps()` method.""" @pytest.fixture def api_response(self): """A typical (shortened) response by the Google Maps Directions API.""" - return [ # noqa:ECE001 + 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,10 +635,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') - def test_sync_instances_with_google_maps(self, db_session, path): + def test_sync_instances_with_google_maps(self, path): """Call the method for a `Path` object without Google data.""" path.bicycle_distance = None path.bicycle_duration = None @@ -665,8 +649,7 @@ class TestSyncWithGoogleMaps: assert path.bicycle_duration == 596 assert path._directions is not None - @pytest.mark.usefixtures('_fake_google_api') - def test_repeated_sync_instances_with_google_maps(self, db_session, path): + def test_repeated_sync_instances_with_google_maps(self, path): """Call the method for a `Path` object with Google data. That call should immediately return without changing any 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 2e8d2ed..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() @@ -376,7 +376,7 @@ class TestConstraints: forecast.low95 = None forecast.high95 = None - forecast.low80, forecast.high80 = ( # noqa:WPS414 + forecast.low80, forecast.high80 = ( forecast.high80, forecast.low80, ) @@ -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() @@ -398,7 +398,7 @@ class TestConstraints: forecast.low80 = None forecast.high80 = None - forecast.low95, forecast.high95 = ( # noqa:WPS414 + forecast.low95, forecast.high95 = ( forecast.high95, forecast.low95, ) @@ -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() @@ -416,13 +416,13 @@ class TestConstraints: assert forecast.low80 is not None assert forecast.low95 is not None - forecast.low80, forecast.low95 = (forecast.low95, forecast.low80) # noqa:WPS414 + forecast.low80, forecast.low95 = (forecast.low95, forecast.low80) db_session.add(forecast) with pytest.raises( sa_exc.IntegrityError, - match='ci95_must_be_wider_than_ci80', + match="ci95_must_be_wider_than_ci80", ): db_session.commit() @@ -431,7 +431,7 @@ class TestConstraints: assert forecast.high80 is not None assert forecast.high95 is not None - forecast.high80, forecast.high95 = ( # noqa:WPS414 + forecast.high80, forecast.high95 = ( forecast.high95, forecast.high80, ) @@ -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 f8d740c..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() @@ -83,10 +83,10 @@ class TestGridification: all considered `Order.pickup_address` attributes for some orders. """ mock = mocker.Mock() - query = ( # noqa:ECE001 - mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501,WPS219 + 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 @@ -105,7 +105,7 @@ class TestGridification: result = db.Grid.gridify(city=city, side_length=side_length) assert isinstance(result, db.Grid) - assert len(result.pixels) == 0 # noqa:WPS507 + assert len(result.pixels) == 0 def test_one_pixel_with_one_address(self, city, order, addresses_mock): """At the very least, there must be one `Pixel` ... @@ -155,7 +155,7 @@ class TestGridification: result = db.Grid.gridify(city=city, side_length=side_length) assert isinstance(result, db.Grid) - assert len(result.pixels) == 0 # noqa:WPS507 + assert len(result.pixels) == 0 @pytest.mark.no_cover def test_no_pixel_with_one_address_too_far_west(self, city, order, addresses_mock): @@ -174,7 +174,7 @@ class TestGridification: result = db.Grid.gridify(city=city, side_length=side_length) assert isinstance(result, db.Grid) - assert len(result.pixels) == 0 # noqa:WPS507 + assert len(result.pixels) == 0 @pytest.mark.no_cover def test_two_pixels_with_two_addresses(self, city, make_address, addresses_mock): @@ -205,8 +205,8 @@ class TestGridification: @pytest.mark.db @pytest.mark.no_cover - @pytest.mark.parametrize('side_length', [250, 500, 1_000, 2_000, 4_000, 8_000]) - def test_make_random_grids( # noqa:WPS211,WPS218 + @pytest.mark.parametrize("side_length", [250, 500, 1_000, 2_000, 4_000, 8_000]) + def test_make_random_grids( self, db_session, city, diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index a95799f..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,25 +405,25 @@ 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( # noqa:WPS213 + def test_unset_timestamp_column_not_marked_as_uncorrected( self, db_session, order, @@ -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,24 +490,24 @@ 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( # noqa:WPS213 + def test_set_timestamp_column_is_not_unmarked( self, db_session, order, @@ -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): @@ -860,18 +860,18 @@ class TestProperties: assert result > dt.timedelta(0) - def test_scheduled_pickup_at_no_restaurant_notified(self, order): # noqa:WPS118 + def test_scheduled_pickup_at_no_restaurant_notified(self, order): """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): # noqa:WPS118 + 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): @@ -952,18 +952,18 @@ class TestProperties: assert bool(result) is False - def test_time_to_delivery_no_reached_delivery_at(self, order): # noqa:WPS118 + def test_time_to_delivery_no_reached_delivery_at(self, order): """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): @@ -972,18 +972,18 @@ class TestProperties: assert result > dt.timedelta(0) - def test_time_at_delivery_no_reached_delivery_at(self, order): # noqa:WPS118 + def test_time_at_delivery_no_reached_delivery_at(self, order): """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): @@ -1083,7 +1083,7 @@ class TestProperties: @pytest.mark.db @pytest.mark.no_cover -def test_make_random_orders( # noqa:C901,WPS211,WPS213 +def test_make_random_orders( # noqa:C901 db_session, make_address, make_courier, @@ -1094,9 +1094,9 @@ def test_make_random_orders( # noqa:C901,WPS211,WPS213 Ensure that all generated `Address`, `Courier`, `Customer`, `Restaurant`, and `Order` objects adhere to the database constraints. - """ # noqa:D202 + """ # Generate a large number of `Order`s to obtain a large variance of data. - for _ in range(1_000): # noqa:WPS122 + for _ in range(1_000): # Ad-hoc `Order`s are far more common than pre-orders. scheduled = random.choice([True, False, False, False, False]) diff --git a/tests/db/test_pixels.py b/tests/db/test_pixels.py index a6a0039..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() @@ -121,20 +121,20 @@ class TestProperties: def _restaurants_mock(self, mocker, monkeypatch, restaurant): """A `Mock` whose `.return_value` is `[restaurant]`.""" mock = mocker.Mock() - query = ( # noqa:ECE001 - mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501,WPS219 + query = ( + 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 b777718..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): @@ -98,7 +98,7 @@ class TestSpecialMethods: def test_compare_utm_coordinates_to_themselves(self, location): """Test `Location.__eq__()`.""" - result = location == location # noqa:WPS312 + result = location == location assert result is True @@ -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 00b4b15..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,21 +207,21 @@ 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]) - def test_decompose_time_series_with_no_demand( # noqa:WPS211,WPS216 + @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, nt, @@ -233,7 +233,7 @@ class TestValidArguments: jt, jl, ni, - no, # noqa:WPS110 + no, ): """Decomposing a time series with no demand ... @@ -252,7 +252,7 @@ class TestValidArguments: jt=jt, jl=jl, ni=ni, - no=no, # noqa:WPS110 + no=no, ) result = decomposed.sum().sum() 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 4821ac2..f741ba1 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. @@ -29,7 +29,7 @@ class TestGenericForecastingModelProperties: So, these test cases are more like integration tests conceptually. Also, note that some `methods.*.predict()` functions use R behind the scenes. - """ # noqa:RST215 + """ def test_create_model(self, model_cls, order_history): """Test instantiation of a new and concrete `*Model` object.""" @@ -52,7 +52,7 @@ class TestGenericForecastingModelProperties: Important: this test case has a side effect that is visible across the different parametrized versions of this case! - """ # noqa:RST215 + """ model = model_cls(order_history=order_history) assert model.name not in self.unique_model_names @@ -70,7 +70,7 @@ class TestGenericForecastingModelProperties: """`*Model.predict()` returns a `pd.DataFrame` ... ... with known columns. - """ # noqa:RST215 + """ model = model_cls(order_history=order_history) result = model.predict( @@ -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 @@ -100,7 +100,7 @@ class TestGenericForecastingModelProperties: """`*Model.predict()` returns a row for ... ... the time step starting at `predict_at`. - """ # noqa:RST215 + """ model = model_cls(order_history=order_history) result = model.predict( @@ -122,7 +122,7 @@ class TestGenericForecastingModelProperties: """`*Model.predict()` returns a `pd.DataFrame` ... ... where the "actual" and "prediction" columns must not be empty. - """ # noqa:RST215 + """ model = model_cls(order_history=order_history) result = model.predict( @@ -131,20 +131,20 @@ 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 - def test_make_forecast( # noqa:WPS211 + @pytest.mark.usefixtures("db_session") + def test_make_forecast( self, - db_session, model_cls, order_history, pixel, predict_at, ): - """`*Model.make_forecast()` returns a `Forecast` object.""" # noqa:RST215 + """`*Model.make_forecast()` returns a `Forecast` object.""" model = model_cls(order_history=order_history) result = model.make_forecast( @@ -160,7 +160,7 @@ class TestGenericForecastingModelProperties: @pytest.mark.db @pytest.mark.r - def test_make_forecast_is_cached( # noqa:WPS211 + def test_make_forecast_is_cached( self, db_session, model_cls, @@ -168,7 +168,7 @@ class TestGenericForecastingModelProperties: pixel, predict_at, ): - """`*Model.make_forecast()` caches the `Forecast` object.""" # noqa:RST215 + """`*Model.make_forecast()` caches the `Forecast` object.""" model = model_cls(order_history=order_history) assert db_session.query(db.Forecast).count() == 0 diff --git a/tests/forecasts/timify/test_aggregate_orders.py b/tests/forecasts/timify/test_aggregate_orders.py index 3a2534a..6c60a06 100644 --- a/tests/forecasts/timify/test_aggregate_orders.py +++ b/tests/forecasts/timify/test_aggregate_orders.py @@ -26,10 +26,10 @@ class TestAggregateOrders: Note: This fixture also exists in `tests.db.test_grids`. """ mock = mocker.Mock() - query = ( # noqa:ECE001 - mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501,WPS219 + 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 @@ -54,7 +54,7 @@ class TestAggregateOrders: def test_no_orders(self, db_session, one_pixel_grid, restaurant): """Edge case that does not occur for real-life data.""" db_session.commit() - assert len(restaurant.orders) == 0 # noqa:WPS507 sanity check + assert len(restaurant.orders) == 0 # sanity check oh = timify.OrderHistory( grid=one_pixel_grid, @@ -63,7 +63,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - assert len(result) == 0 # noqa:WPS507 + assert len(result) == 0 def test_evenly_distributed_ad_hoc_orders( self, @@ -95,11 +95,11 @@ 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( # noqa:WPS218 + def test_evenly_distributed_ad_hoc_orders_with_no_demand_late( self, db_session, one_pixel_grid, @@ -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,11 +208,11 @@ 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( # noqa:WPS218 + def test_evenly_distributed_ad_hoc_orders_with_half_hour_time_steps( self, db_session, one_pixel_grid, @@ -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, @@ -273,7 +273,7 @@ class TestAggregateOrders: db_session.add(order) # Create one order every other hour and 6 orders in total. - for hour in range(11, 23, 2): # noqa:WPS440 + for hour in range(11, 23, 2): order = make_order( scheduled=False, restaurant=restaurant, @@ -281,7 +281,7 @@ class TestAggregateOrders: test_config.YEAR, test_config.MONTH, test_config.DAY + 1, - hour, # noqa:WPS441 + hour, 11, ), ) @@ -300,12 +300,12 @@ 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( # noqa:WPS211 + def two_pixel_grid( self, db_session, city, @@ -336,7 +336,7 @@ class TestAggregateOrders: return grid - def test_two_pixels_with_shifted_orders( # noqa:WPS218 + def test_two_pixels_with_shifted_orders( self, db_session, two_pixel_grid, @@ -361,7 +361,7 @@ class TestAggregateOrders: db_session.add(order) # Create two orders per hour for `restaurant2`. - for hour in range(11, 23): # noqa:WPS440 + for hour in range(11, 23): order = make_order( scheduled=False, restaurant=restaurant2, @@ -369,7 +369,7 @@ class TestAggregateOrders: test_config.YEAR, test_config.MONTH, test_config.DAY, - hour, # noqa:WPS441 + hour, 13, ), ) @@ -382,7 +382,7 @@ class TestAggregateOrders: test_config.YEAR, test_config.MONTH, test_config.DAY, - hour, # noqa:WPS441 + hour, 14, ), ) @@ -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 86ede7f..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[ # noqa:ECE001 + 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[ # noqa:ECE001 + 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[ # noqa:ECE001 + 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, @@ -150,13 +150,13 @@ class TestChooseTacticalModel: self, order_history, good_pixel_id, - predict_at, # noqa:RST215 + predict_at, ): """For `train_horizon` values not included in the rule-based system ... ... 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 98f73e0..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, @@ -119,11 +119,11 @@ class TestMakeHorizontalTimeSeries: train_horizon=train_horizon, ) - _, frequency, _ = result # noqa:WPS434 + _, frequency, _ = result 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, @@ -243,7 +243,7 @@ class TestMakeVerticalTimeSeries: train_horizon=train_horizon, ) - _, frequency, _ = result # noqa:WPS434 + _, frequency, _ = result n_daily_time_steps = ( 60 @@ -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, @@ -423,7 +423,7 @@ class TestMakeRealTimeTimeSeries: train_horizon=train_horizon, ) - _, frequency, _ = result # noqa:WPS434 + _, frequency, _ = result n_daily_time_steps = ( 60 @@ -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..c122628 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 @@ -70,11 +70,11 @@ class TestMethods: assert result == test_config.START - def test_first_order_at_non_existing_pixel(self, order_history, good_pixel_id): + def test_first_order_at_non_existing_pixel(self, order_history): """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) @@ -85,10 +85,10 @@ class TestMethods: one_time_step = dt.timedelta(minutes=test_config.LONG_TIME_STEP) assert result == test_config.END - one_time_step - def test_last_order_at_non_existing_pixel(self, order_history, good_pixel_id): + def test_last_order_at_non_existing_pixel(self, order_history): """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 84bc883..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 # noqa:WPS441,WPS507 + 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 # noqa:WPS441,WPS507 + 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 # noqa:WPS441,WPS507 + 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 # noqa:WPS441,WPS507 + 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_init_r.py b/tests/test_init_r.py index da82254..7a6755a 100644 --- a/tests/test_init_r.py +++ b/tests/test_init_r.py @@ -14,6 +14,6 @@ def test_r_packages_installed(): in the "research/r_dependencies.ipynb" notebook or in the GitHub Actions CI. """ - from velofy import init_r # noqa:WPS433 + from velofy import init_r assert init_r is not None diff --git a/tests/test_version.py b/tests/test_version.py index a4870e5..bc3fde0 100644 --- a/tests/test_version.py +++ b/tests/test_version.py @@ -23,7 +23,7 @@ class TestPEP404Compliance: @pytest.fixture def parsed_version(self) -> str: """The packaged version.""" - return pkg_version.Version(velofy.__version__) # noqa:WPS609 + return pkg_version.Version(velofy.__version__) def test_parsed_version_has_no_epoch(self, parsed_version): """PEP440 compliant subset of semantic versioning: no epoch.""" @@ -39,36 +39,36 @@ class TestPEP404Compliance: def test_parsed_version_is_all_public(self, parsed_version): """PEP440 compliant subset of semantic versioning: all public parts.""" - assert parsed_version.public == velofy.__version__ # noqa:WPS609 + assert parsed_version.public == velofy.__version__ 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): """Packaged version follows semantic versioning.""" - result = self.version_pattern.fullmatch(velofy.__version__) # noqa:WPS609 + result = self.version_pattern.fullmatch(velofy.__version__) assert result is not None # 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): diff --git a/uv.lock b/uv.lock index e10bfbe..ee0e488 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.13, <4.0" resolution-markers = [ "python_full_version >= '3.15' and sys_platform == 'win32'", @@ -247,6 +247,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/3b/ddf4b07be846bfa361683729b5948c9c61a87fbdf09e69540d8e586bb7c5/babel-2.19.0-py3-none-any.whl", hash = "sha256:6d49734aed1d595b2c065d012174df8c83964692f26fc461702281634dd7555b", size = 10983582, upload-time = "2026-11-24T20:14:30.163Z" }, ] +[[package]] +name = "bandit" +version = "1.9.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "pyyaml" }, + { name = "rich" }, + { name = "stevedore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/aa/c3/0cb80dfe0f3076e5da7e4c5ad8e57bac6ac357ff4a6406205501cade4965/bandit-1.9.4.tar.gz", hash = "sha256:b589e5de2afe70bd4d53fa0c1da6199f4085af666fde00e8a034f152a52cd628", size = 4242677, upload-time = "2026-02-25T06:44:15.503Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/a4/a26d5b25671d27e03afb5401a0be5899d94ff8fab6a698b1ac5be3ec29ef/bandit-1.9.4-py3-none-any.whl", hash = "sha256:f89ffa663767f5a0585ea075f01020207e966a9c0f2b9ef56a57c7963a3f6f8e", size = 134741, upload-time = "2026-02-25T06:44:13.694Z" }, +] + [[package]] name = "beautifulsoup4" version = "4.15.0" @@ -786,6 +801,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/2b/238f02a4927fa2e27aa995371d240a468b52e42eae44a678434aff736b38/distlib-0.4.4-py2.py3-none-any.whl", hash = "sha256:cf09d55b1e85a89576b036aeb71550bfd68320f3f21761ca329eadadad918638", size = 472099, upload-time = "2026-10-16T13:56:32.053Z" }, ] +[[package]] +name = "docstring-parser-fork" +version = "0.0.16" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/04/ce/48b17c6c24d0af112f73721a90fac245450e548b82b53169260720f60d07/docstring_parser_fork-0.0.16.tar.gz", hash = "sha256:9ecf861ceab8b87d1297a71001c15a1956ad02e87434ee6473643a5988094f7c", size = 36360, upload-time = "2026-07-03T07:27:46.668Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/69/427c34e61827818942b48ececd7c892b8f58ba4ce4cfc89ba9fd8dbe8a8d/docstring_parser_fork-0.0.16-py3-none-any.whl", hash = "sha256:c024c97af582d6acf85a14f0b332b3a2ab08626648d251c25e47191f33064386", size = 25253, upload-time = "2026-07-03T07:27:45.591Z" }, +] + [[package]] name = "docutils" version = "0.23" @@ -872,6 +896,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f4/2b/ef0b4b0927b9f3a7034d3a76ee6e150c4b40459a8704132793cac43537be/flake8_annotations-3.3.1-py3-none-any.whl", hash = "sha256:64c926ccce95da4f666db6b04a7bfc8892118671a2b10cc339bbba9acf91ca70", size = 17264, upload-time = "2026-10-29T23:43:36.898Z" }, ] +[[package]] +name = "flake8-bandit" +version = "4.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "bandit" }, + { name = "flake8" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/77/1c/4f66a7a52a246d6c64312b5c40da3af3630cd60b27af81b137796af3c0bc/flake8_bandit-4.1.1.tar.gz", hash = "sha256:068e09287189cbfd7f986e92605adea2067630b75380c6b5733dab7d87f9a84e", size = 5403, upload-time = "2022-08-29T13:48:41.225Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/5f/55bab0ac89f9ad9f4c6e38087faa80c252daec4ccb7776b4dac216ca9e3f/flake8_bandit-4.1.1-py3-none-any.whl", hash = "sha256:4c8a53eb48f23d4ef1e59293657181a3c989d0077c9952717e98a0eace43e06d", size = 4828, upload-time = "2022-08-29T13:48:39.737Z" }, +] + [[package]] name = "flake8-black" version = "0.5.0" @@ -885,6 +922,81 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/00/ba/8950a5ef5180c089f5ae474b60555acb0c079bc2b5dd55b7e8193e01be87/flake8_black-0.5.0-py3-none-any.whl", hash = "sha256:28c16f3c5421d1831ce27177926dbaa1d6d460da475afdcd230d409c35495ae7", size = 10167, upload-time = "2026-11-03T11:59:13.491Z" }, ] +[[package]] +name = "flake8-broken-line" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/30/5e/eca08446205afb79e74b6af8e227f06f0b1a26ae892708adbc4e65ccaa86/flake8_broken_line-1.0.0.tar.gz", hash = "sha256:e2c6a17f8d9a129e99c1320fce89b33843e2963871025c4c2bb7b8b8d8732a85", size = 3458, upload-time = "2023-05-31T10:09:11.716Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/ff/57d0101933527b5202cc9f80bc15aa85b207916c722a00e7adde0e33f413/flake8_broken_line-1.0.0-py3-none-any.whl", hash = "sha256:96c964336024a5030dc536a9f6fb02aa679e2d2a6b35b80a558b5136c35832a9", size = 4202, upload-time = "2023-05-31T10:09:10.027Z" }, +] + +[[package]] +name = "flake8-bugbear" +version = "26.11.22" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "flake8" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/26/b4/2d6c97486396d8ab985537ce01de9048cff21b6c3f9d0029d261e1017132/flake8_bugbear-26.11.22.tar.gz", hash = "sha256:df1a764570a3047deb99c6c1309679277815ef48d7c9dada7e04973e2b327a10", size = 148709, upload-time = "2026-11-22T14:25:52.305Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/ba/da7d4108baed185aecfc0c8cc8e64b2964f92a1897d3310b79c168ac94d3/flake8_bugbear-26.11.22-py3-none-any.whl", hash = "sha256:bc10d62be1dc512dc7825ee34c20492425370b209e47fb09a1dedd29eba49aca", size = 65763, upload-time = "2026-11-22T14:25:51.217Z" }, +] + +[[package]] +name = "flake8-commas" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/e7/4add4247c9ea7871f6bc9f794f2771647b809bb492b36c8ce18825d64994/flake8_commas-4.0.0.tar.gz", hash = "sha256:a68834b42a9a31c94ca790efe557a932c0eae21a3479c6b9a23c4dc077e3ea96", size = 9338, upload-time = "2024-05-16T20:07:46.271Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/74/d4/75d1cdd7c89cb6af4f956393c339bb9a7d203999432a823f60b64c0ea072/flake8_commas-4.0.0-py3-none-any.whl", hash = "sha256:cad476d71ba72e8b941a8508d5b9ffb6b03e50f7102982474f085ad0d674b685", size = 7877, upload-time = "2024-05-16T20:07:44.536Z" }, +] + +[[package]] +name = "flake8-comprehensions" +version = "3.17.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/91/93/da2d30987ce4c06404326e7c8e6636cae18c2b2f2d5542891a8ad64a34f4/flake8_comprehensions-3.17.0.tar.gz", hash = "sha256:bf4fa102b2bf4d6c9e999e29e4b2724cbadffb70b937600fc782161be4dc0f4a", size = 13269, upload-time = "2025-09-09T22:37:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/bd/d6739d685fdd79349aa51c37bdedc0d8eab6ae9c6e6ed2ca935b3f88210d/flake8_comprehensions-3.17.0-py3-none-any.whl", hash = "sha256:3943a9c6f2593c3bc5cc64106c2f89d63c6ecd49c8343597f8257b8fcfc8b0a2", size = 8185, upload-time = "2025-09-09T22:37:17.149Z" }, +] + +[[package]] +name = "flake8-debugger" +version = "4.1.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, + { name = "pycodestyle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1f/1e/f9bdb98f3df5dceaa2287a8fb5801a22681dbd677a8759704083357e27c4/flake8-debugger-4.1.2.tar.gz", hash = "sha256:52b002560941e36d9bf806fca2523dc7fb8560a295d5f1a6e15ac2ded7a73840", size = 7801, upload-time = "2022-04-30T16:50:55.71Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/6b/8e5d248949798644b3d8e5f598ed5d1da82d8f157d4bafd78f45247f1690/flake8_debugger-4.1.2-py3-none-any.whl", hash = "sha256:0a5e55aeddcc81da631ad9c8c366e7318998f83ff00985a49e6b3ecf61e571bf", size = 7909, upload-time = "2022-04-30T16:50:57.294Z" }, +] + +[[package]] +name = "flake8-docstrings" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, + { name = "pydocstyle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/93/24/f839e3a06e18f4643ccb81370909a497297909f15106e6af2fecdef46894/flake8_docstrings-1.7.0.tar.gz", hash = "sha256:4c8cc748dc16e6869728699e5d0d685da9a10b0ea718e090b1ba088e67a941af", size = 5995, upload-time = "2023-01-25T14:27:13.903Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/7d/76a278fa43250441ed9300c344f889c7fb1817080c8fb8996b840bf421c2/flake8_docstrings-1.7.0-py2.py3-none-any.whl", hash = "sha256:51f2344026da083fc084166a9353f5082b01f72901df422f74b4d953ae88ac75", size = 4994, upload-time = "2023-01-25T14:27:12.32Z" }, +] + [[package]] name = "flake8-plugin-utils" version = "1.3.3" @@ -917,6 +1029,53 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4d/de/36523c4defc0d02f1617de66e23cd18ad74b869d401269bba6d790abc95e/flake8_pytest_style-2.2.0-py3-none-any.whl", hash = "sha256:d01c4198a6c4e0ab759a92a0fa7710f10d83ec28e32a50ab6fb2e10f973a2f36", size = 22370, upload-time = "2025-10-20T07:52:23.82Z" }, ] +[[package]] +name = "flake8-quotes" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, + { name = "setuptools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/dd/57/a173e3eb86072b7ee77650aca496b15d6886367d257f58ea9de5276e330a/flake8-quotes-3.4.0.tar.gz", hash = "sha256:aad8492fb710a2d3eabe68c5f86a1428de650c8484127e14c43d0504ba30276c", size = 14107, upload-time = "2024-02-10T21:58:22.357Z" } + +[[package]] +name = "flake8-sfs" +version = "1.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/10/d0/f382713010bb429934fd03b9b0cc8726ef620719fec49c942e8fc41454e7/flake8_sfs-1.0.1.tar.gz", hash = "sha256:0cab211f805efe2b29a8480fda0d46a8cedba1d45b4dd71b9bd0675804097149", size = 6531, upload-time = "2025-09-21T09:31:42.454Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/a8/dc3b3dbe52808d3f09504950d20963a3e19ab1bf6492790b70b8b2e32565/flake8_sfs-1.0.1-py3-none-any.whl", hash = "sha256:ef5f6b3e6d958894fe4c953ecf8e6156d9ab620c7e138f68af5c0f9bfdb4f6b4", size = 6651, upload-time = "2025-09-21T09:31:41.166Z" }, +] + +[[package]] +name = "flake8-todos" +version = "0.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, + { name = "pycodestyle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/88/69/e4ecde7f50c3c874046f03dc7bda67d7be8e7cc28380f3f44c07456b45ad/flake8_todos-0.3.1.tar.gz", hash = "sha256:942101a08f831d7d9f7d864d86169f3bcfaf8b6d56a004c0280eb51725266b16", size = 7851, upload-time = "2024-02-09T08:50:45.907Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/8e/805907f920d171eda033ac825d23595072a1c04dd716106c8bc8ec9eec9e/flake8_todos-0.3.1-py3-none-any.whl", hash = "sha256:0b4faca80bec49be7bf8e5dd46eec12f619e09cecac8a84a87775272300222b2", size = 7358, upload-time = "2024-02-09T08:50:43.66Z" }, +] + +[[package]] +name = "flake8-unused-arguments" +version = "0.0.14" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1b/6a/12e072814ac64c4ed18c039738d97e7326df1352f696f16872aa0cea482c/flake8_unused_arguments-0.0.14.tar.gz", hash = "sha256:5b6cac6ecb325c0d5460edc6c52e2861c146eca03ddedc36dcb32beafeacbbec", size = 5514, upload-time = "2025-10-27T22:22:55.946Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/0b/1d658aca231a3e4b3c0b9e7fed71ced551cbfd955a41cfd32b221b396edc/flake8_unused_arguments-0.0.14-py3-none-any.whl", hash = "sha256:6c0b7ce7236a156f4bd90adec67ad0e5d0139efcd15c2a1fc0fb3a6ffd7e435e", size = 6190, upload-time = "2025-10-27T22:22:54.888Z" }, +] + [[package]] name = "folium" version = "1.0.0" @@ -1689,6 +1848,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/6d/a0/053d6af3e8f871e0073b4a36732d9e65be77a72e5434c31b94f6af78a6bb/mako-1.4.3-py3-none-any.whl", hash = "sha256:723296007c870bfd6b3f0c3230dba7198096e5269297ebf5e4eff9e7ffa39d4f", size = 80164, upload-time = "2026-09-22T20:54:33.128Z" }, ] +[[package]] +name = "markdown-it-py" +version = "4.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/16/fc/cee2c45553c9a9bf77d8b0c391560c556d7ed756b1f0bb35eb5d48db09ea/markdown_it_py-4.3.0.tar.gz", hash = "sha256:91a58fa5b72c71a40cf7177250fd767480d7a2bb3ac426ccfb76fb90305fdaaa", size = 242701, upload-time = "2026-11-10T16:18:30.467Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/31/5f0ac2f1a1c67423c995c731a11cd4ad05d081a2be969d74f868bdb9cc70/markdown_it_py-4.3.0-py3-none-any.whl", hash = "sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa", size = 96951, upload-time = "2026-11-10T16:18:28.975Z" }, +] + [[package]] name = "markupsafe" version = "3.0.4" @@ -1862,6 +2033,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/27/1a/1f68f9ba0c207934b35b86a8ca3aad8395a3d6dd7921c0686e23853ff5a9/mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e", size = 7350, upload-time = "2022-01-24T01:14:49.62Z" }, ] +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + [[package]] name = "mistune" version = "3.4.0" @@ -2215,6 +2395,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/20/70/cd3cf5cff538323076a879edef02cce6f13f7d75e03d12f211b0a0dbd178/patsy-1.0.3-py2.py3-none-any.whl", hash = "sha256:d3dbebe8fd5f46e29912d030b63c6268647b59bf788a99e2af28a30234cf357c", size = 233318, upload-time = "2026-08-29T21:35:30.913Z" }, ] +[[package]] +name = "pep8-naming" +version = "0.15.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flake8" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8d/59/c32862134635ba231d45f1711035550dc38246396c27269a4cde4bfe18d2/pep8_naming-0.15.1.tar.gz", hash = "sha256:f6f4a499aba2deeda93c1f26ccc02f3da32b035c8b2db9696b730ef2c9639d29", size = 17640, upload-time = "2025-05-05T20:43:12.555Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a6/78/25281540f1121acaa78926f599a17ce102b8971bc20b096fa7fb6b5b59c1/pep8_naming-0.15.1-py3-none-any.whl", hash = "sha256:eb63925e7fd9e028c7f7ee7b1e413ec03d1ee5de0e627012102ee0222c273c86", size = 9561, upload-time = "2025-05-05T20:43:11.626Z" }, +] + [[package]] name = "pexpect" version = "4.9.0" @@ -2465,6 +2657,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b6/ae/315bbeee126a769cbde43cf4908acb4b40408d8bf8bbf334dd7368d8dadf/pycparser-3.12-py3-none-any.whl", hash = "sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e", size = 62600, upload-time = "2026-10-22T13:40:02.021Z" }, ] +[[package]] +name = "pydoclint" +version = "0.12.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "docstring-parser-fork" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9b/f7/ae03ad83f47dfee8a468544e4b77b254940299b15f9710e00450a5034729/pydoclint-0.12.0.tar.gz", hash = "sha256:ac061ae24381547e41d5a45044a1f88c87a54541b67ec959bd5160c69256482c", size = 255216, upload-time = "2026-10-28T06:48:34.428Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6e/45/9aea4898fcfbb3ed973eb23f6b83c677bb8bcecb59e9681fae6da82bb3be/pydoclint-0.12.0-py3-none-any.whl", hash = "sha256:28f5763a865cb19b54883dfe68b05b01d2c2fc2e8d59dcf424cc345bc976a689", size = 99545, upload-time = "2026-10-28T06:48:33.34Z" }, +] + +[package.optional-dependencies] +flake8 = [ + { name = "flake8" }, +] + +[[package]] +name = "pydocstyle" +version = "6.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "snowballstemmer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/5c/d5385ca59fd065e3c6a5fe19f9bc9d5ea7f2509fa8c9c22fb6b2031dd953/pydocstyle-6.3.0.tar.gz", hash = "sha256:7ce43f0c0ac87b07494eb9c0b462c0b73e6ff276807f204d6b53edc72b7e44e1", size = 36796, upload-time = "2023-01-17T20:29:19.838Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/36/ea/99ddefac41971acad68f14114f38261c1f27dac0b3ec529824ebc739bdaa/pydocstyle-6.3.0-py3-none-any.whl", hash = "sha256:118762d452a49d6b05e194ef344a55822987a462831ade91ec5c06fd2169d019", size = 38038, upload-time = "2023-01-17T20:29:18.094Z" }, +] + [[package]] name = "pyflakes" version = "4.1.0" @@ -2803,6 +3025,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/71/44ce230e1b7fadd372515a97e32a83011f906ddded8d03e3c6aafbdedbb7/rfc3987_syntax-1.1.0-py3-none-any.whl", hash = "sha256:6c3d97604e4c5ce9f714898e05401a0445a641cfa276432b0a648c80856f6a3f", size = 8046, upload-time = "2025-07-18T01:05:03.843Z" }, ] +[[package]] +name = "rich" +version = "15.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, +] + [[package]] name = "roman-numerals" version = "4.1.0" @@ -3007,6 +3242,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b2/de/7a9e77bd4c5f6eb11d90eb75807c1e1f0ea54997b05ae86d6fc5fa080c04/send2trash-2.2.0-py3-none-any.whl", hash = "sha256:7f540296d59744fbf2f88b0d6f3a484af78c94d3c20e0875a4d5eed61aef037c", size = 17436, upload-time = "2026-11-12T00:35:18.674Z" }, ] +[[package]] +name = "setuptools" +version = "84.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" }, +] + [[package]] name = "shapely" version = "2.2.0" @@ -3315,6 +3559,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e3/eb/90a506dbee5cde669e2ef28565ff6b7a0791ab415eab2da82f92d033cccc/statsmodels-0.15.0-cp315-cp315t-win_arm64.whl", hash = "sha256:90df413d7e09474f7e7cbf8807440c1bf76298cdd9daabf9141f76d7627c9151", size = 11021454, upload-time = "2026-08-30T16:06:08.124Z" }, ] +[[package]] +name = "stevedore" +version = "5.10.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/ec/b628c3b1613fe9340de1c5daba957f5b152159ac350b6ce4ad3d2469f822/stevedore-5.10.0.tar.gz", hash = "sha256:6005f32c09dc3159802a61c04862770e439e32db22f6da78ba56e8a735466882", size = 520466, upload-time = "2026-11-12T11:47:05.38Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/78/918aaff2864a8829d061db40acb9da04c89e5c3a01d65932b34432ebd78b/stevedore-5.10.0-py3-none-any.whl", hash = "sha256:47c48dc09e75933106c1bba0a7690eef3b5acecdb807df6d47cc40b2532fa927", size = 56789, upload-time = "2026-11-12T11:47:04.273Z" }, +] + [[package]] name = "terminado" version = "0.18.1" @@ -3461,6 +3714,7 @@ wheels = [ name = "velofy" version = "0.5.0.dev0" source = { editable = "." } +default-groups = "all" dependencies = [ { name = "alembic" }, { name = "click" }, @@ -3491,13 +3745,26 @@ dev = [ { name = "black" }, { name = "flake8" }, { name = "flake8-annotations" }, + { name = "flake8-bandit" }, { name = "flake8-black" }, + { name = "flake8-broken-line" }, + { name = "flake8-bugbear" }, + { name = "flake8-commas" }, + { name = "flake8-comprehensions" }, + { name = "flake8-debugger" }, + { name = "flake8-docstrings" }, { name = "flake8-pyproject" }, { name = "flake8-pytest-style" }, + { name = "flake8-quotes" }, + { name = "flake8-sfs" }, + { name = "flake8-todos" }, + { name = "flake8-unused-arguments" }, { name = "isort" }, { name = "mypy" }, { name = "nox" }, + { name = "pep8-naming" }, { name = "pre-commit" }, + { name = "pydoclint", extra = ["flake8"] }, ] docs = [ { name = "sphinx" }, @@ -3542,13 +3809,26 @@ dev = [ { name = "black", specifier = ">=25.12.0,<26.0.0" }, { name = "flake8", specifier = ">=7.5.0,<8.0.0" }, { name = "flake8-annotations", specifier = ">=3.3.1,<4.0.0" }, + { name = "flake8-bandit", specifier = ">=4.1.1,<5.0.0" }, { name = "flake8-black", specifier = ">=0.5.0,<0.6.0" }, + { name = "flake8-broken-line", specifier = ">=1.0.0,<2.0.0" }, + { name = "flake8-bugbear", specifier = ">=26.11.22,<27.0.0" }, + { name = "flake8-commas", specifier = ">=4.0.0,<5.0.0" }, + { name = "flake8-comprehensions", specifier = ">=3.17.0,<4.0.0" }, + { name = "flake8-debugger", specifier = ">=4.1.2,<5.0.0" }, + { name = "flake8-docstrings", specifier = ">=1.7.0,<2.0.0" }, { name = "flake8-pyproject", specifier = ">=1.2.4,<2.0.0" }, { name = "flake8-pytest-style", specifier = ">=2.2.0,<3.0.0" }, + { name = "flake8-quotes", specifier = ">=3.4.0,<4.0.0" }, + { name = "flake8-sfs", specifier = ">=1.0.1,<2.0.0" }, + { name = "flake8-todos", specifier = ">=0.3.1,<0.4.0" }, + { name = "flake8-unused-arguments", specifier = ">=0.0.14,<0.1.0" }, { name = "isort", specifier = ">=9.0.2,<10.0.0" }, { name = "mypy", specifier = ">=2.4.1,<3.0.0" }, { name = "nox", specifier = ">=2026.10.20" }, + { name = "pep8-naming", specifier = ">=0.15.1,<0.16.0" }, { name = "pre-commit", specifier = ">=4.7.0,<5.0.0" }, + { name = "pydoclint", extras = ["flake8"], specifier = ">=0.12.0,<0.13.0" }, ] docs = [ { name = "sphinx", specifier = ">=9.2.0,<10.0.0" },