Remove wemake-python-styleguide #5

Merged
alexander merged 25 commits from remove-wps into develop 2026-11-28 04:16:02 +01:00
90 changed files with 3048 additions and 2838 deletions

5
.git-blame-ignore-revs Normal file
View file

@ -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

View file

@ -19,12 +19,16 @@ repos:
- repo: local - repo: local
hooks: hooks:
# `require_serial: true`
# => Parallel runs would recreate the same `nox` environment
- id: local-format - id: local-format
name: Format the source files name: Format the source files
entry: uv run nox -s format -- entry: uv run nox -s format --
language: unsupported language: unsupported
stages: [pre-commit] stages: [pre-commit]
types: [python] types: [python]
require_serial: true
- id: local-lint - id: local-lint
name: Lint the source files name: Lint the source files
@ -32,6 +36,7 @@ repos:
language: unsupported language: unsupported
stages: [pre-commit] stages: [pre-commit]
types: [python] types: [python]
require_serial: true
- id: local-test - id: local-test
name: Run the test suite name: Run the test suite
@ -40,6 +45,7 @@ repos:
stages: [pre-merge-commit] stages: [pre-merge-commit]
pass_filenames: false # => No `--` at the end of the "entry" pass_filenames: false # => No `--` at the end of the "entry"
always_run: true always_run: true
require_serial: true
- id: local-doctest - id: local-doctest
name: Run the doctests name: Run the doctests
@ -48,6 +54,7 @@ repos:
stages: [pre-merge-commit] stages: [pre-merge-commit]
pass_filenames: false # => No `--` at the end of the "entry" pass_filenames: false # => No `--` at the end of the "entry"
always_run: true always_run: true
require_serial: true
# Keep requirements.txt in sync with uv.lock # Keep requirements.txt in sync with uv.lock
- repo: https://github.com/astral-sh/uv-pre-commit - repo: https://github.com/astral-sh/uv-pre-commit

View file

@ -5,11 +5,11 @@ import velofy
project = velofy.__pkg_name__ project = velofy.__pkg_name__
author = velofy.__author__ author = velofy.__author__
copyright = f'2020, {author}' copyright = f"2020, {author}"
version = release = velofy.__version__ version = release = velofy.__version__
extensions = [ extensions = [
'sphinx.ext.autodoc', "sphinx.ext.autodoc",
'sphinx.ext.napoleon', "sphinx.ext.napoleon",
'sphinx_autodoc_typehints', "sphinx_autodoc_typehints",
] ]

View file

@ -12,7 +12,7 @@ from velofy import db
# Disable the --sql option, a.k.a, the "offline mode". # Disable the --sql option, a.k.a, the "offline mode".
if context.is_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. # 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): def include_object(obj, _name, type_, _reflected, _compare_to):
"""Only include the clean schema into --autogenerate migrations.""" """Only include the clean schema into --autogenerate migrations."""
if ( # noqa:WPS337 if (
type_ in {'table', 'column'} type_ in {"table", "column"}
and hasattr(obj, 'schema') # noqa:WPS421 => fix for rare edge case and hasattr(obj, "schema") # => fix for rare edge case
and obj.schema != velofy_config.CLEAN_SCHEMA and obj.schema != velofy_config.CLEAN_SCHEMA
): ):
return False return False
@ -33,17 +33,14 @@ def include_object(obj, _name, type_, _reflected, _compare_to):
engine = sa.create_engine(velofy_config.DATABASE_URI) 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: with engine.connect() as connection:
context.configure( context.configure(
connection=connection, connection=connection,
include_object=include_object, include_object=include_object,
target_metadata=db.Base.metadata, target_metadata=db.Base.metadata,
version_table='{alembic_table}{test_schema}'.format( version_table=f"{velofy_config.ALEMBIC_TABLE}{test_schema}",
alembic_table=velofy_config.ALEMBIC_TABLE,
test_schema=(
f'_{velofy_config.CLEAN_SCHEMA}' if os.getenv('TESTING') else ''
),
),
version_table_schema=velofy_config.ALEMBIC_TABLE_SCHEMA, version_table_schema=velofy_config.ALEMBIC_TABLE_SCHEMA,
) )

View file

@ -12,141 +12,141 @@ from alembic import op
from velofy import configuration from velofy import configuration
revision = '888e352d7526' revision = "888e352d7526"
down_revision = 'f11cd76d2f45' down_revision = "f11cd76d2f45"
branch_labels = None branch_labels = None
depends_on = 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(): def upgrade():
"""Upgrade to revision 888e352d7526.""" """Upgrade to revision 888e352d7526."""
op.create_table( op.create_table(
'grids', "grids",
sa.Column('id', sa.SmallInteger(), autoincrement=True, nullable=False), sa.Column("id", sa.SmallInteger(), autoincrement=True, nullable=False),
sa.Column('city_id', sa.SmallInteger(), nullable=False), sa.Column("city_id", sa.SmallInteger(), nullable=False),
sa.Column('side_length', sa.SmallInteger(), nullable=True), sa.Column("side_length", sa.SmallInteger(), nullable=True),
sa.PrimaryKeyConstraint('id', name=op.f('pk_grids')), sa.PrimaryKeyConstraint("id", name=op.f("pk_grids")),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['city_id'], ["city_id"],
[f'{config.CLEAN_SCHEMA}.cities.id'], [f"{config.CLEAN_SCHEMA}.cities.id"],
name=op.f('fk_grids_to_cities_via_city_id'), name=op.f("fk_grids_to_cities_via_city_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.UniqueConstraint( sa.UniqueConstraint(
'city_id', "city_id",
'side_length', "side_length",
name=op.f('uq_grids_on_city_id_side_length'), name=op.f("uq_grids_on_city_id_side_length"),
), ),
# This `UniqueConstraint` is needed by the `addresses_pixels` table below. # 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, schema=config.CLEAN_SCHEMA,
) )
op.create_table( op.create_table(
'pixels', "pixels",
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column('grid_id', sa.SmallInteger(), nullable=False), sa.Column("grid_id", sa.SmallInteger(), nullable=False),
sa.Column('n_x', sa.SmallInteger(), nullable=False), sa.Column("n_x", sa.SmallInteger(), nullable=False),
sa.Column('n_y', 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_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.CheckConstraint("0 <= n_y", name=op.f("ck_pixels_on_n_y_is_positive")),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['grid_id'], ["grid_id"],
[f'{config.CLEAN_SCHEMA}.grids.id'], [f"{config.CLEAN_SCHEMA}.grids.id"],
name=op.f('fk_pixels_to_grids_via_grid_id'), name=op.f("fk_pixels_to_grids_via_grid_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.PrimaryKeyConstraint('id', name=op.f('pk_pixels')), sa.PrimaryKeyConstraint("id", name=op.f("pk_pixels")),
sa.UniqueConstraint( sa.UniqueConstraint(
'grid_id', "grid_id",
'n_x', "n_x",
'n_y', "n_y",
name=op.f('uq_pixels_on_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, schema=config.CLEAN_SCHEMA,
) )
op.create_index( op.create_index(
op.f('ix_pixels_on_grid_id'), op.f("ix_pixels_on_grid_id"),
'pixels', "pixels",
['grid_id'], ["grid_id"],
unique=False, unique=False,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_index( op.create_index(
op.f('ix_pixels_on_n_x'), op.f("ix_pixels_on_n_x"),
'pixels', "pixels",
['n_x'], ["n_x"],
unique=False, unique=False,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_index( op.create_index(
op.f('ix_pixels_on_n_y'), op.f("ix_pixels_on_n_y"),
'pixels', "pixels",
['n_y'], ["n_y"],
unique=False, unique=False,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
# This `UniqueConstraint` is needed by the `addresses_pixels` table below. # This `UniqueConstraint` is needed by the `addresses_pixels` table below.
op.create_unique_constraint( op.create_unique_constraint(
'uq_addresses_on_id_city_id', "uq_addresses_on_id_city_id",
'addresses', "addresses",
['id', 'city_id'], ["id", "city_id"],
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_table( op.create_table(
'addresses_pixels', "addresses_pixels",
sa.Column('address_id', sa.Integer(), nullable=False), sa.Column("address_id", sa.Integer(), nullable=False),
sa.Column('city_id', sa.SmallInteger(), nullable=False), sa.Column("city_id", sa.SmallInteger(), nullable=False),
sa.Column('grid_id', sa.SmallInteger(), nullable=False), sa.Column("grid_id", sa.SmallInteger(), nullable=False),
sa.Column('pixel_id', sa.Integer(), nullable=False), sa.Column("pixel_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['address_id', 'city_id'], ["address_id", "city_id"],
[ [
f'{config.CLEAN_SCHEMA}.addresses.id', f"{config.CLEAN_SCHEMA}.addresses.id",
f'{config.CLEAN_SCHEMA}.addresses.city_id', f"{config.CLEAN_SCHEMA}.addresses.city_id",
], ],
name=op.f('fk_addresses_pixels_to_addresses_via_address_id_city_id'), name=op.f("fk_addresses_pixels_to_addresses_via_address_id_city_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['grid_id', 'city_id'], ["grid_id", "city_id"],
[ [
f'{config.CLEAN_SCHEMA}.grids.id', f"{config.CLEAN_SCHEMA}.grids.id",
f'{config.CLEAN_SCHEMA}.grids.city_id', f"{config.CLEAN_SCHEMA}.grids.city_id",
], ],
name=op.f('fk_addresses_pixels_to_grids_via_grid_id_city_id'), name=op.f("fk_addresses_pixels_to_grids_via_grid_id_city_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['pixel_id', 'grid_id'], ["pixel_id", "grid_id"],
[ [
f'{config.CLEAN_SCHEMA}.pixels.id', f"{config.CLEAN_SCHEMA}.pixels.id",
f'{config.CLEAN_SCHEMA}.pixels.grid_id', f"{config.CLEAN_SCHEMA}.pixels.grid_id",
], ],
name=op.f('fk_addresses_pixels_to_pixels_via_pixel_id_grid_id'), name=op.f("fk_addresses_pixels_to_pixels_via_pixel_id_grid_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.PrimaryKeyConstraint( sa.PrimaryKeyConstraint(
'address_id', "address_id",
'pixel_id', "pixel_id",
name=op.f('pk_addresses_pixels'), name=op.f("pk_addresses_pixels"),
), ),
sa.UniqueConstraint( sa.UniqueConstraint(
'address_id', "address_id",
'grid_id', "grid_id",
name=op.f('uq_addresses_pixels_on_address_id_grid_id'), name=op.f("uq_addresses_pixels_on_address_id_grid_id"),
), ),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
@ -154,27 +154,27 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision f11cd76d2f45.""" """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( op.drop_constraint(
'uq_addresses_on_id_city_id', "uq_addresses_on_id_city_id",
'addresses', "addresses",
type_=None, type_=None,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_index( op.drop_index(
op.f('ix_pixels_on_n_y'), op.f("ix_pixels_on_n_y"),
table_name='pixels', table_name="pixels",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_index( op.drop_index(
op.f('ix_pixels_on_n_x'), op.f("ix_pixels_on_n_x"),
table_name='pixels', table_name="pixels",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_index( op.drop_index(
op.f('ix_pixels_on_grid_id'), op.f("ix_pixels_on_grid_id"),
table_name='pixels', table_name="pixels",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_table('pixels', schema=config.CLEAN_SCHEMA) op.drop_table("pixels", schema=config.CLEAN_SCHEMA)
op.drop_table('grids', schema=config.CLEAN_SCHEMA) op.drop_table("grids", schema=config.CLEAN_SCHEMA)

View file

@ -13,33 +13,33 @@ from sqlalchemy.dialects import postgresql
from velofy import configuration from velofy import configuration
revision = 'e40623e10405' revision = "e40623e10405"
down_revision = '888e352d7526' down_revision = "888e352d7526"
branch_labels = None branch_labels = None
depends_on = 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(): def upgrade():
"""Upgrade to revision e40623e10405.""" """Upgrade to revision e40623e10405."""
op.create_table( op.create_table(
'forecasts', "forecasts",
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column('pixel_id', sa.Integer(), nullable=False), sa.Column("pixel_id", sa.Integer(), nullable=False),
sa.Column('start_at', sa.DateTime(), nullable=False), sa.Column("start_at", sa.DateTime(), nullable=False),
sa.Column('time_step', sa.SmallInteger(), nullable=False), sa.Column("time_step", sa.SmallInteger(), nullable=False),
sa.Column('training_horizon', sa.SmallInteger(), nullable=False), sa.Column("training_horizon", sa.SmallInteger(), nullable=False),
sa.Column('method', sa.Unicode(length=20), nullable=False), sa.Column("method", sa.Unicode(length=20), nullable=False),
sa.Column('prediction', postgresql.DOUBLE_PRECISION(), nullable=False), sa.Column("prediction", postgresql.DOUBLE_PRECISION(), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_forecasts')), sa.PrimaryKeyConstraint("id", name=op.f("pk_forecasts")),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['pixel_id'], ["pixel_id"],
[f'{config.CLEAN_SCHEMA}.pixels.id'], [f"{config.CLEAN_SCHEMA}.pixels.id"],
name=op.f('fk_forecasts_to_pixels_via_pixel_id'), name=op.f("fk_forecasts_to_pixels_via_pixel_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.CheckConstraint( sa.CheckConstraint(
""" """
@ -49,44 +49,44 @@ def upgrade():
EXTRACT(HOUR FROM start_at) > 22 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( sa.CheckConstraint(
'CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0', "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'), name=op.f("ck_forecasts_on_start_at_minutes_must_be_quarters_of_the_hour"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0', "CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0",
name=op.f('ck_forecasts_on_start_at_allows_no_microseconds'), name=op.f("ck_forecasts_on_start_at_allows_no_microseconds"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'EXTRACT(SECONDS FROM start_at) = 0', "EXTRACT(SECONDS FROM start_at) = 0",
name=op.f('ck_forecasts_on_start_at_allows_no_seconds'), name=op.f("ck_forecasts_on_start_at_allows_no_seconds"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'time_step > 0', "time_step > 0",
name=op.f('ck_forecasts_on_time_step_must_be_positive'), name=op.f("ck_forecasts_on_time_step_must_be_positive"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'training_horizon > 0', "training_horizon > 0",
name=op.f('ck_forecasts_on_training_horizon_must_be_positive'), name=op.f("ck_forecasts_on_training_horizon_must_be_positive"),
), ),
sa.UniqueConstraint( sa.UniqueConstraint(
'pixel_id', "pixel_id",
'start_at', "start_at",
'time_step', "time_step",
'training_horizon', "training_horizon",
'method', "method",
name=op.f( 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, schema=config.CLEAN_SCHEMA,
) )
op.create_index( op.create_index(
op.f('ix_forecasts_on_pixel_id'), op.f("ix_forecasts_on_pixel_id"),
'forecasts', "forecasts",
['pixel_id'], ["pixel_id"],
unique=False, unique=False,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
@ -94,4 +94,4 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision 888e352d7526.""" """Downgrade to revision 888e352d7526."""
op.drop_table('forecasts', schema=config.CLEAN_SCHEMA) op.drop_table("forecasts", schema=config.CLEAN_SCHEMA)

View file

@ -13,46 +13,46 @@ from sqlalchemy.dialects import postgresql
from velofy import configuration from velofy import configuration
revision = '26711cd3f9b9' revision = "26711cd3f9b9"
down_revision = 'e40623e10405' down_revision = "e40623e10405"
branch_labels = None branch_labels = None
depends_on = 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(): def upgrade():
"""Upgrade to revision 26711cd3f9b9.""" """Upgrade to revision 26711cd3f9b9."""
op.alter_column( op.alter_column(
'forecasts', "forecasts",
'method', "method",
new_column_name='model', new_column_name="model",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.add_column( op.add_column(
'forecasts', "forecasts",
sa.Column('low80', postgresql.DOUBLE_PRECISION(), nullable=True), sa.Column("low80", postgresql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.add_column( op.add_column(
'forecasts', "forecasts",
sa.Column('high80', postgresql.DOUBLE_PRECISION(), nullable=True), sa.Column("high80", postgresql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.add_column( op.add_column(
'forecasts', "forecasts",
sa.Column('low95', postgresql.DOUBLE_PRECISION(), nullable=True), sa.Column("low95", postgresql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.add_column( op.add_column(
'forecasts', "forecasts",
sa.Column('high95', postgresql.DOUBLE_PRECISION(), nullable=True), sa.Column("high95", postgresql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_check_constraint( op.create_check_constraint(
op.f('ck_forecasts_on_ci_upper_and_lower_bounds'), op.f("ck_forecasts_on_ci_upper_and_lower_bounds"),
'forecasts', "forecasts",
""" """
NOT ( NOT (
low80 IS NULL AND high80 IS NOT NULL low80 IS NULL AND high80 IS NOT NULL
@ -67,8 +67,8 @@ def upgrade():
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_check_constraint( op.create_check_constraint(
op.f('prediction_must_be_within_ci'), op.f("prediction_must_be_within_ci"),
'forecasts', "forecasts",
""" """
NOT ( NOT (
prediction < low80 prediction < low80
@ -83,8 +83,8 @@ def upgrade():
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_check_constraint( op.create_check_constraint(
op.f('ci_upper_bound_greater_than_lower_bound'), op.f("ci_upper_bound_greater_than_lower_bound"),
'forecasts', "forecasts",
""" """
NOT ( NOT (
low80 > high80 low80 > high80
@ -95,8 +95,8 @@ def upgrade():
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_check_constraint( op.create_check_constraint(
op.f('ci95_must_be_wider_than_ci80'), op.f("ci95_must_be_wider_than_ci80"),
'forecasts', "forecasts",
""" """
NOT ( NOT (
low80 < low95 low80 < low95
@ -111,28 +111,28 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision e40623e10405.""" """Downgrade to revision e40623e10405."""
op.alter_column( op.alter_column(
'forecasts', "forecasts",
'model', "model",
new_column_name='method', new_column_name="method",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_column( op.drop_column(
'forecasts', "forecasts",
'low80', "low80",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_column( op.drop_column(
'forecasts', "forecasts",
'high80', "high80",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_column( op.drop_column(
'forecasts', "forecasts",
'low95', "low95",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_column( op.drop_column(
'forecasts', "forecasts",
'high95', "high95",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )

View file

@ -129,13 +129,13 @@ from alembic import op
from velofy import configuration from velofy import configuration
revision = 'e86290e7305e' revision = "e86290e7305e"
down_revision = '26711cd3f9b9' down_revision = "26711cd3f9b9"
branch_labels = None branch_labels = None
depends_on = 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(): def upgrade():
@ -347,26 +347,26 @@ def upgrade():
""", """,
) )
op.create_unique_constraint( op.create_unique_constraint(
'uq_restaurants_on_id_address_id', "uq_restaurants_on_id_address_id",
'restaurants', "restaurants",
['id', 'address_id'], ["id", "address_id"],
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_foreign_key( op.create_foreign_key(
op.f('fk_orders_to_restaurants_via_restaurant_id_pickup_address_id'), op.f("fk_orders_to_restaurants_via_restaurant_id_pickup_address_id"),
'orders', "orders",
'restaurants', "restaurants",
['restaurant_id', 'pickup_address_id'], ["restaurant_id", "pickup_address_id"],
['id', 'address_id'], ["id", "address_id"],
source_schema=config.CLEAN_SCHEMA, source_schema=config.CLEAN_SCHEMA,
referent_schema=config.CLEAN_SCHEMA, referent_schema=config.CLEAN_SCHEMA,
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
) )
op.drop_constraint( op.drop_constraint(
'fk_orders_to_restaurants_via_restaurant_id', "fk_orders_to_restaurants_via_restaurant_id",
'orders', "orders",
type_='foreignkey', type_="foreignkey",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
@ -374,25 +374,25 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision 26711cd3f9b9.""" """Downgrade to revision 26711cd3f9b9."""
op.create_foreign_key( op.create_foreign_key(
op.f('fk_orders_to_restaurants_via_restaurant_id'), op.f("fk_orders_to_restaurants_via_restaurant_id"),
'orders', "orders",
'restaurants', "restaurants",
['restaurant_id'], ["restaurant_id"],
['id'], ["id"],
source_schema=config.CLEAN_SCHEMA, source_schema=config.CLEAN_SCHEMA,
referent_schema=config.CLEAN_SCHEMA, referent_schema=config.CLEAN_SCHEMA,
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
) )
op.drop_constraint( op.drop_constraint(
'fk_orders_to_restaurants_via_restaurant_id_pickup_address_id', "fk_orders_to_restaurants_via_restaurant_id_pickup_address_id",
'orders', "orders",
type_='foreignkey', type_="foreignkey",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.drop_constraint( op.drop_constraint(
'uq_restaurants_on_id_address_id', "uq_restaurants_on_id_address_id",
'restaurants', "restaurants",
type_='unique', type_="unique",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )

View file

@ -12,30 +12,30 @@ from alembic import op
from velofy import configuration from velofy import configuration
revision = 'c2af85bada01' revision = "c2af85bada01"
down_revision = 'e86290e7305e' down_revision = "e86290e7305e"
branch_labels = None branch_labels = None
depends_on = 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(): def upgrade():
"""Upgrade to revision c2af85bada01.""" """Upgrade to revision c2af85bada01."""
op.add_column( op.add_column(
'forecasts', "forecasts",
sa.Column('actual', sa.SmallInteger(), nullable=False), sa.Column("actual", sa.SmallInteger(), nullable=False),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_check_constraint( op.create_check_constraint(
op.f('ck_forecasts_on_actuals_must_be_non_negative'), op.f("ck_forecasts_on_actuals_must_be_non_negative"),
'forecasts', "forecasts",
'actual >= 0', "actual >= 0",
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
def downgrade(): def downgrade():
"""Downgrade to revision e86290e7305e.""" """Downgrade to revision e86290e7305e."""
op.drop_column('forecasts', 'actual', schema=config.CLEAN_SCHEMA) op.drop_column("forecasts", "actual", schema=config.CLEAN_SCHEMA)

View file

@ -11,13 +11,13 @@ from alembic import op
from velofy import configuration from velofy import configuration
revision = '8bfb928a31f8' revision = "8bfb928a31f8"
down_revision = 'c2af85bada01' down_revision = "c2af85bada01"
branch_labels = None branch_labels = None
depends_on = 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(): def upgrade():
@ -31,7 +31,7 @@ def upgrade():
TO TO
train_horizon; train_horizon;
""", """,
) # noqa:WPS355 )
def downgrade(): def downgrade():
@ -45,4 +45,4 @@ def downgrade():
TO TO
training_horizon; training_horizon;
""", """,
) # noqa:WPS355 )

View file

@ -13,79 +13,79 @@ from sqlalchemy.dialects import postgresql
from velofy import configuration from velofy import configuration
revision = 'b4dd0b8903a5' revision = "b4dd0b8903a5"
down_revision = '8bfb928a31f8' down_revision = "8bfb928a31f8"
branch_labels = None branch_labels = None
depends_on = 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(): def upgrade():
"""Upgrade to revision b4dd0b8903a5.""" """Upgrade to revision b4dd0b8903a5."""
op.create_table( op.create_table(
'addresses_addresses', "addresses_addresses",
sa.Column('first_address_id', sa.Integer(), nullable=False), sa.Column("first_address_id", sa.Integer(), nullable=False),
sa.Column('second_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("city_id", sa.SmallInteger(), nullable=False),
sa.Column('air_distance', sa.Integer(), nullable=False), sa.Column("air_distance", sa.Integer(), nullable=False),
sa.Column('bicycle_distance', sa.Integer(), nullable=True), sa.Column("bicycle_distance", sa.Integer(), nullable=True),
sa.Column('bicycle_duration', sa.Integer(), nullable=True), sa.Column("bicycle_duration", sa.Integer(), nullable=True),
sa.Column('directions', postgresql.JSON(), nullable=True), sa.Column("directions", postgresql.JSON(), nullable=True),
sa.PrimaryKeyConstraint( sa.PrimaryKeyConstraint(
'first_address_id', "first_address_id",
'second_address_id', "second_address_id",
name=op.f('pk_addresses_addresses'), name=op.f("pk_addresses_addresses"),
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['first_address_id', 'city_id'], ["first_address_id", "city_id"],
[ [
f'{config.CLEAN_SCHEMA}.addresses.id', f"{config.CLEAN_SCHEMA}.addresses.id",
f'{config.CLEAN_SCHEMA}.addresses.city_id', f"{config.CLEAN_SCHEMA}.addresses.city_id",
], ],
name=op.f( 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', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['second_address_id', 'city_id'], ["second_address_id", "city_id"],
[ [
f'{config.CLEAN_SCHEMA}.addresses.id', f"{config.CLEAN_SCHEMA}.addresses.id",
f'{config.CLEAN_SCHEMA}.addresses.city_id', f"{config.CLEAN_SCHEMA}.addresses.city_id",
], ],
name=op.f( 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', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.UniqueConstraint( sa.UniqueConstraint(
'first_address_id', "first_address_id",
'second_address_id', "second_address_id",
name=op.f('uq_addresses_addresses_on_first_address_id_second_address_id'), name=op.f("uq_addresses_addresses_on_first_address_id_second_address_id"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'first_address_id < second_address_id', "first_address_id < second_address_id",
name=op.f('ck_addresses_addresses_on_distances_are_symmetric_for_bicycles'), name=op.f("ck_addresses_addresses_on_distances_are_symmetric_for_bicycles"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'0 <= air_distance AND air_distance < 20000', "0 <= air_distance AND air_distance < 20000",
name=op.f('ck_addresses_addresses_on_realistic_air_distance'), name=op.f("ck_addresses_addresses_on_realistic_air_distance"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'bicycle_distance < 25000', "bicycle_distance < 25000",
name=op.f('ck_addresses_addresses_on_realistic_bicycle_distance'), name=op.f("ck_addresses_addresses_on_realistic_bicycle_distance"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'air_distance <= bicycle_distance', "air_distance <= bicycle_distance",
name=op.f('ck_addresses_addresses_on_air_distance_is_shortest'), name=op.f("ck_addresses_addresses_on_air_distance_is_shortest"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'0 <= bicycle_duration AND bicycle_duration <= 3600', "0 <= bicycle_duration AND bicycle_duration <= 3600",
name=op.f('ck_addresses_addresses_on_realistic_bicycle_travel_time'), name=op.f("ck_addresses_addresses_on_realistic_bicycle_travel_time"),
), ),
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
@ -93,4 +93,4 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision 8bfb928a31f8.""" """Downgrade to revision 8bfb928a31f8."""
op.drop_table('addresses_addresses', schema=config.CLEAN_SCHEMA) op.drop_table("addresses_addresses", schema=config.CLEAN_SCHEMA)

View file

@ -12,13 +12,13 @@ from alembic import op
from velofy import configuration from velofy import configuration
revision = '81aa304d7a6e' revision = "81aa304d7a6e"
down_revision = 'b4dd0b8903a5' down_revision = "b4dd0b8903a5"
branch_labels = None branch_labels = None
depends_on = 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(): def upgrade():
@ -29,7 +29,7 @@ def upgrade():
ALTER TABLE {config.CLEAN_SCHEMA}.orders ALTER TABLE {config.CLEAN_SCHEMA}.orders
DROP CONSTRAINT ck_orders_on_ordered_timestamps_21; DROP CONSTRAINT ck_orders_on_ordered_timestamps_21;
""", """,
) # noqa:WPS355 )
# Add forgotten check constraints to the `orders` table. # Add forgotten check constraints to the `orders` table.
op.execute( op.execute(
@ -38,7 +38,7 @@ def upgrade():
ADD CONSTRAINT check_orders_on_ordered_timestamps_placed_at_before_pickup_at ADD CONSTRAINT check_orders_on_ordered_timestamps_placed_at_before_pickup_at
CHECK (placed_at < pickup_at); CHECK (placed_at < pickup_at);
""", """,
) # noqa:WPS355 )
op.execute( op.execute(
f""" f"""
ALTER TABLE {config.CLEAN_SCHEMA}.orders ALTER TABLE {config.CLEAN_SCHEMA}.orders
@ -55,92 +55,92 @@ def upgrade():
) )
); );
""", """,
) # noqa:WPS355 )
# This `UniqueConstraint` is needed by the `replayed_orders` table below. # This `UniqueConstraint` is needed by the `replayed_orders` table below.
op.create_unique_constraint( op.create_unique_constraint(
'uq_orders_on_id_ad_hoc', "uq_orders_on_id_ad_hoc",
'orders', "orders",
['id', 'ad_hoc'], ["id", "ad_hoc"],
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_table( op.create_table(
'replay_simulations', "replay_simulations",
sa.Column('id', sa.Integer, autoincrement=True), sa.Column("id", sa.Integer, autoincrement=True),
sa.Column('city_id', sa.SmallInteger, nullable=False), sa.Column("city_id", sa.SmallInteger, nullable=False),
sa.Column('strategy', sa.Unicode(length=100), nullable=False), sa.Column("strategy", sa.Unicode(length=100), nullable=False),
sa.Column('run', sa.SmallInteger, nullable=False), sa.Column("run", sa.SmallInteger, nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_replay_simulations')), sa.PrimaryKeyConstraint("id", name=op.f("pk_replay_simulations")),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['city_id'], ["city_id"],
[f'{config.CLEAN_SCHEMA}.cities.id'], [f"{config.CLEAN_SCHEMA}.cities.id"],
name=op.f('fk_replay_simulations_to_cities_via_city_id'), name=op.f("fk_replay_simulations_to_cities_via_city_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.UniqueConstraint( sa.UniqueConstraint(
'city_id', "city_id",
'strategy', "strategy",
'run', "run",
name=op.f('uq_replay_simulations_on_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, schema=config.CLEAN_SCHEMA,
) )
op.create_table( op.create_table(
'replayed_orders', "replayed_orders",
sa.Column('simulation_id', sa.Integer, primary_key=True), sa.Column("simulation_id", sa.Integer, primary_key=True),
sa.Column('actual_order_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("ad_hoc", sa.Boolean, nullable=False),
sa.Column('placed_at', sa.DateTime, nullable=False), sa.Column("placed_at", sa.DateTime, nullable=False),
sa.Column('scheduled_delivery_at', sa.DateTime), sa.Column("scheduled_delivery_at", sa.DateTime),
sa.Column('cancelled_at', sa.DateTime), sa.Column("cancelled_at", sa.DateTime),
sa.Column('estimated_prep_duration', sa.SmallInteger), sa.Column("estimated_prep_duration", sa.SmallInteger),
sa.Column('restaurant_notified_at', sa.DateTime), sa.Column("restaurant_notified_at", sa.DateTime),
sa.Column('restaurant_confirmed_at', sa.DateTime), sa.Column("restaurant_confirmed_at", sa.DateTime),
sa.Column('restaurant_ready_at', sa.DateTime), sa.Column("restaurant_ready_at", sa.DateTime),
sa.Column('dispatch_at', sa.DateTime), sa.Column("dispatch_at", sa.DateTime),
sa.Column('first_estimated_delivery_at', sa.DateTime), sa.Column("first_estimated_delivery_at", sa.DateTime),
sa.Column('courier_id', sa.Integer), sa.Column("courier_id", sa.Integer),
sa.Column('courier_notified_at', sa.DateTime), sa.Column("courier_notified_at", sa.DateTime),
sa.Column('courier_accepted_at', sa.DateTime), sa.Column("courier_accepted_at", sa.DateTime),
sa.Column('utilization', sa.SmallInteger), sa.Column("utilization", sa.SmallInteger),
sa.Column('reached_pickup_at', sa.DateTime), sa.Column("reached_pickup_at", sa.DateTime),
sa.Column('pickup_at', sa.DateTime), sa.Column("pickup_at", sa.DateTime),
sa.Column('left_pickup_at', sa.DateTime), sa.Column("left_pickup_at", sa.DateTime),
sa.Column('reached_delivery_at', sa.DateTime), sa.Column("reached_delivery_at", sa.DateTime),
sa.Column('delivery_at', sa.DateTime), sa.Column("delivery_at", sa.DateTime),
sa.PrimaryKeyConstraint( sa.PrimaryKeyConstraint(
'simulation_id', "simulation_id",
'actual_order_id', "actual_order_id",
name=op.f('pk_replayed_orders'), name=op.f("pk_replayed_orders"),
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['simulation_id'], ["simulation_id"],
[f'{config.CLEAN_SCHEMA}.replay_simulations.id'], [f"{config.CLEAN_SCHEMA}.replay_simulations.id"],
name=op.f('fk_replayed_orders_to_replay_simulations_via_simulation_id'), name=op.f("fk_replayed_orders_to_replay_simulations_via_simulation_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
# Needs the `UniqueConstraint` from above. # 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.id",
f'{config.CLEAN_SCHEMA}.orders.ad_hoc', f"{config.CLEAN_SCHEMA}.orders.ad_hoc",
], ],
name=op.f('fk_replayed_orders_to_orders_via_actual_order_id_ad_hoc'), name=op.f("fk_replayed_orders_to_orders_via_actual_order_id_ad_hoc"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.ForeignKeyConstraint( sa.ForeignKeyConstraint(
['courier_id'], ["courier_id"],
[f'{config.CLEAN_SCHEMA}.couriers.id'], [f"{config.CLEAN_SCHEMA}.couriers.id"],
name=op.f('fk_replayed_orders_to_couriers_via_courier_id'), name=op.f("fk_replayed_orders_to_couriers_via_courier_id"),
onupdate='RESTRICT', onupdate="RESTRICT",
ondelete='RESTRICT', ondelete="RESTRICT",
), ),
sa.CheckConstraint( sa.CheckConstraint(
""" """
@ -156,7 +156,7 @@ def upgrade():
scheduled_delivery_at IS NOT NULL 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( 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( 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( sa.CheckConstraint(
""" """
@ -204,7 +204,7 @@ def upgrade():
= 0 = 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( sa.CheckConstraint(
""" """
@ -212,7 +212,7 @@ def upgrade():
EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800 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( sa.CheckConstraint(
""" """
@ -244,7 +244,7 @@ def upgrade():
delivery_at IS NOT NULL 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( sa.CheckConstraint(
""" """
@ -272,19 +272,19 @@ def upgrade():
delivery_at IS NOT NULL 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( sa.CheckConstraint(
'0 <= estimated_prep_duration AND estimated_prep_duration <= 3600', "0 <= estimated_prep_duration AND estimated_prep_duration <= 3600",
name=op.f('estimated_prep_duration_between_0_and_3600'), name=op.f("estimated_prep_duration_between_0_and_3600"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'estimated_prep_duration % 60 = 0', "estimated_prep_duration % 60 = 0",
name=op.f('estimated_prep_duration_must_be_whole_minutes'), name=op.f("estimated_prep_duration_must_be_whole_minutes"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
'0 <= utilization AND utilization <= 100', "0 <= utilization AND utilization <= 100",
name=op.f('utilization_between_0_and_100'), name=op.f("utilization_between_0_and_100"),
), ),
sa.CheckConstraint( sa.CheckConstraint(
""" """
@ -294,71 +294,71 @@ def upgrade():
EXTRACT(HOUR FROM dispatch_at) < 11 EXTRACT(HOUR FROM dispatch_at) < 11
) )
""", """,
name=op.f('orders_dispatched_in_business_hours'), name=op.f("orders_dispatched_in_business_hours"),
), ),
*( *(
sa.CheckConstraint( sa.CheckConstraint(
constraint, constraint,
name='ordered_timestamps_{index}'.format(index=index), name=f"ordered_timestamps_{index}",
) )
for index, constraint in enumerate( for index, constraint in enumerate(
( (
'placed_at < scheduled_delivery_at', "placed_at < scheduled_delivery_at",
'placed_at < cancelled_at', "placed_at < cancelled_at",
'placed_at < restaurant_notified_at', "placed_at < restaurant_notified_at",
'placed_at < restaurant_confirmed_at', "placed_at < restaurant_confirmed_at",
'placed_at < restaurant_ready_at', "placed_at < restaurant_ready_at",
'placed_at < dispatch_at', "placed_at < dispatch_at",
'placed_at < first_estimated_delivery_at', "placed_at < first_estimated_delivery_at",
'placed_at < courier_notified_at', "placed_at < courier_notified_at",
'placed_at < courier_accepted_at', "placed_at < courier_accepted_at",
'placed_at < reached_pickup_at', "placed_at < reached_pickup_at",
'placed_at < pickup_at', "placed_at < pickup_at",
'placed_at < left_pickup_at', "placed_at < left_pickup_at",
'placed_at < reached_delivery_at', "placed_at < reached_delivery_at",
'placed_at < delivery_at', "placed_at < delivery_at",
'cancelled_at > restaurant_notified_at', "cancelled_at > restaurant_notified_at",
'cancelled_at > restaurant_confirmed_at', "cancelled_at > restaurant_confirmed_at",
'cancelled_at > restaurant_ready_at', "cancelled_at > restaurant_ready_at",
'cancelled_at > dispatch_at', "cancelled_at > dispatch_at",
'cancelled_at > courier_notified_at', "cancelled_at > courier_notified_at",
'cancelled_at > courier_accepted_at', "cancelled_at > courier_accepted_at",
'cancelled_at > reached_pickup_at', "cancelled_at > reached_pickup_at",
'restaurant_notified_at < restaurant_confirmed_at', "restaurant_notified_at < restaurant_confirmed_at",
'restaurant_notified_at < restaurant_ready_at', "restaurant_notified_at < restaurant_ready_at",
'restaurant_notified_at < pickup_at', "restaurant_notified_at < pickup_at",
'restaurant_confirmed_at < restaurant_ready_at', "restaurant_confirmed_at < restaurant_ready_at",
'restaurant_confirmed_at < pickup_at', "restaurant_confirmed_at < pickup_at",
'restaurant_ready_at < pickup_at', "restaurant_ready_at < pickup_at",
'dispatch_at < first_estimated_delivery_at', "dispatch_at < first_estimated_delivery_at",
'dispatch_at < courier_notified_at', "dispatch_at < courier_notified_at",
'dispatch_at < courier_accepted_at', "dispatch_at < courier_accepted_at",
'dispatch_at < reached_pickup_at', "dispatch_at < reached_pickup_at",
'dispatch_at < pickup_at', "dispatch_at < pickup_at",
'dispatch_at < left_pickup_at', "dispatch_at < left_pickup_at",
'dispatch_at < reached_delivery_at', "dispatch_at < reached_delivery_at",
'dispatch_at < delivery_at', "dispatch_at < delivery_at",
'courier_notified_at < courier_accepted_at', "courier_notified_at < courier_accepted_at",
'courier_notified_at < reached_pickup_at', "courier_notified_at < reached_pickup_at",
'courier_notified_at < pickup_at', "courier_notified_at < pickup_at",
'courier_notified_at < left_pickup_at', "courier_notified_at < left_pickup_at",
'courier_notified_at < reached_delivery_at', "courier_notified_at < reached_delivery_at",
'courier_notified_at < delivery_at', "courier_notified_at < delivery_at",
'courier_accepted_at < reached_pickup_at', "courier_accepted_at < reached_pickup_at",
'courier_accepted_at < pickup_at', "courier_accepted_at < pickup_at",
'courier_accepted_at < left_pickup_at', "courier_accepted_at < left_pickup_at",
'courier_accepted_at < reached_delivery_at', "courier_accepted_at < reached_delivery_at",
'courier_accepted_at < delivery_at', "courier_accepted_at < delivery_at",
'reached_pickup_at < pickup_at', "reached_pickup_at < pickup_at",
'reached_pickup_at < left_pickup_at', "reached_pickup_at < left_pickup_at",
'reached_pickup_at < reached_delivery_at', "reached_pickup_at < reached_delivery_at",
'reached_pickup_at < delivery_at', "reached_pickup_at < delivery_at",
'pickup_at < left_pickup_at', "pickup_at < left_pickup_at",
'pickup_at < reached_delivery_at', "pickup_at < reached_delivery_at",
'pickup_at < delivery_at', "pickup_at < delivery_at",
'left_pickup_at < reached_delivery_at', "left_pickup_at < reached_delivery_at",
'left_pickup_at < delivery_at', "left_pickup_at < delivery_at",
'reached_delivery_at < delivery_at', "reached_delivery_at < delivery_at",
), ),
) )
), ),
@ -366,23 +366,23 @@ def upgrade():
) )
op.create_index( op.create_index(
op.f('ix_replay_simulations_on_city_id'), op.f("ix_replay_simulations_on_city_id"),
'replay_simulations', "replay_simulations",
['city_id'], ["city_id"],
unique=False, unique=False,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_index( op.create_index(
op.f('ix_replay_simulations_on_strategy'), op.f("ix_replay_simulations_on_strategy"),
'replay_simulations', "replay_simulations",
['strategy'], ["strategy"],
unique=False, unique=False,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
op.create_index( op.create_index(
op.f('ix_replayed_orders_on_courier_id'), op.f("ix_replayed_orders_on_courier_id"),
'replayed_orders', "replayed_orders",
['courier_id'], ["courier_id"],
unique=False, unique=False,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
@ -390,11 +390,11 @@ def upgrade():
def downgrade(): def downgrade():
"""Downgrade to revision b4dd0b8903a5.""" """Downgrade to revision b4dd0b8903a5."""
op.drop_table('replayed_orders', schema=config.CLEAN_SCHEMA) op.drop_table("replayed_orders", schema=config.CLEAN_SCHEMA)
op.drop_table('replay_simulations', schema=config.CLEAN_SCHEMA) op.drop_table("replay_simulations", schema=config.CLEAN_SCHEMA)
op.drop_constraint( op.drop_constraint(
'uq_orders_on_id_ad_hoc', "uq_orders_on_id_ad_hoc",
'orders', "orders",
type_=None, type_=None,
schema=config.CLEAN_SCHEMA, schema=config.CLEAN_SCHEMA,
) )
@ -403,17 +403,17 @@ def downgrade():
ALTER TABLE {config.CLEAN_SCHEMA}.orders ALTER TABLE {config.CLEAN_SCHEMA}.orders
DROP CONSTRAINT check_orders_on_scheduled_orders_must_be_at_quarters_of_an_hour; DROP CONSTRAINT check_orders_on_scheduled_orders_must_be_at_quarters_of_an_hour;
""", """,
) # noqa:WPS355 )
op.execute( op.execute(
f""" f"""
ALTER TABLE {config.CLEAN_SCHEMA}.orders ALTER TABLE {config.CLEAN_SCHEMA}.orders
DROP CONSTRAINT check_orders_on_ordered_timestamps_placed_at_before_pickup_at; DROP CONSTRAINT check_orders_on_ordered_timestamps_placed_at_before_pickup_at;
""", """,
) # noqa:WPS355 )
op.execute( op.execute(
f""" f"""
ALTER TABLE {config.CLEAN_SCHEMA}.orders ALTER TABLE {config.CLEAN_SCHEMA}.orders
ADD CONSTRAINT ck_orders_on_ordered_timestamps_21 ADD CONSTRAINT ck_orders_on_ordered_timestamps_21
CHECK (cancelled_at > delivery_at); CHECK (cancelled_at > delivery_at);
""", """,
) # noqa:WPS355 )

View file

@ -15,7 +15,7 @@ Further sessions run on demand with `uv run nox -s <session>`:
- "deps-lock": Lock dependencies after manual changes in pyproject.toml - "deps-lock": Lock dependencies after manual changes in pyproject.toml
- "deps-upgrade": Upgrade dependencies within their allowed ranges - "deps-upgrade": Upgrade dependencies within their allowed ranges
- "deps-upgrade-check": Show newer versions and the age of all pinned releases - "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 - "clean-cwd": Run approx. `git clean -X` with minor exceptions
Most sessions accept extra arguments after the "--", 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) so, missing keys and tables (i.e., "sections" in the .ini format)
do not result in `KeyError`s but return empty `nested_defaultdict`s. 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]: def load_supported_python_versions(*, reverse: bool = False) -> list[str]:
"""Parse the Python versions from the pyproject.toml file.""" """Parse the Python versions from the pyproject.toml file."""
pyproject = load_pyproject_toml() pyproject = load_pyproject_toml()
version_names = { version_names = {
classifier.rsplit(' ')[-1] classifier.rsplit(" ")[-1]
for classifier in pyproject['project']['classifiers'] for classifier in pyproject["project"]["classifiers"]
if classifier.startswith('Programming Language :: Python :: ') if classifier.startswith("Programming Language :: Python :: ")
} }
return sorted(version_names, key=pkg_version.Version, reverse=reverse) return sorted(version_names, key=pkg_version.Version, reverse=reverse)
PACKAGE = 'velofy' PACKAGE = "velofy"
PACKAGE_LOCATION = 'src/' PACKAGE_LOCATION = "src/"
DOCS_BUILD = '.cache/docs/' DOCS_BUILD = ".cache/docs/"
DOCS_LOCATION = 'docs/' DOCS_LOCATION = "docs/"
TESTS_LOCATION = 'tests/' TESTS_LOCATION = "tests/"
# Locations of all *.py files # Locations of all *.py files
SRC_LOCATIONS = ( SRC_LOCATIONS = (
f'{DOCS_LOCATION}conf.py', f"{DOCS_LOCATION}conf.py",
'migrations/env.py', "migrations/env.py",
'migrations/versions/', "migrations/versions/",
'noxfile.py', "./noxfile.py", # The "./" keeps `bandit` from warning about its module name
'scripts/', "scripts/",
PACKAGE_LOCATION, PACKAGE_LOCATION,
TESTS_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 # Must be listed in the "classifiers", which is checked at the bottom
# of this file, and satisfy "requires-python" in pyproject.toml # 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 # 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 # All tools except `git` and `uv` are project dependencies
# => Avoid accidental successes if the environment is not set up properly # => 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 # Always start with fresh virtual environments
# unless the "-r" or "-R" flags are passed in # 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 # Do not run further sessions once one fails
nox.options.stop_on_first_error = True nox.options.stop_on_first_error = True
# Run only the code quality checks by default # Run only the code quality checks by default
nox.options.sessions = ( nox.options.sessions = (
'format', "format",
'lint', "lint",
'test', "test",
'doctest', "doctest",
) )
# Make `uv` use its own `python` # Make `uv` use its own `python`
# because only then are the headers needed to build `rpy2` from source included # 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()`) # 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) 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: def format_code(session: Session) -> None:
"""Format source files with `autoflake`, `black`, and `isort`. """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 # The formatters do not need `velofy` installed
# because they work on the source files directly # 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 # Interpret extra arguments as `locations` of source files
locations = session.posargs or SRC_LOCATIONS locations = session.posargs or SRC_LOCATIONS
# `autoflake` changes files only with the "in-place = true" # `autoflake` changes files only with the "in-place = true"
# in the "[tool.autoflake]" section in pyproject.toml # in the "[tool.autoflake]" section in pyproject.toml
session.run('autoflake', '--version') session.run("autoflake", "--version")
session.run('autoflake', *locations) session.run("autoflake", *locations)
session.run('black', '--version') session.run("black", "--version")
session.run('black', *locations) session.run("black", *locations)
session.run('isort', '--version') session.run("isort", "--version")
session.run('isort', *locations) session.run("isort", *locations)
@nox.session(name='lint', python=MAIN_PYTHON) @nox.session(name="lint", python=MAIN_PYTHON)
def lint_code(session: Session) -> None: def lint_code(session: Session) -> None:
"""Lint source files with `flake8` and `isort`. """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 # because they work on the source files directly
install_pinned( install_pinned(
session, session,
'flake8', "flake8",
'flake8-annotations', "flake8-annotations",
'flake8-black', "flake8-bandit",
'flake8-pyproject', "flake8-black",
'flake8-pytest-style', "flake8-broken-line",
'isort', "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 # TODO: See comment on `mypy` below
# 'mypy', # 'mypy',
"pep8-naming",
"pydoclint[flake8]",
) )
# Interpret extra arguments as `locations` of source files # 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 # `flake8` reads the "[tool.flake8]" section in pyproject.toml
# only with the `flake8-pyproject` plugin installed # only with the `flake8-pyproject` plugin installed
session.run('flake8', '--version') session.run("flake8", "--version")
session.run('flake8', *locations) session.run("flake8", *locations)
session.run('isort', '--version') session.run("isort", "--version")
session.run('isort', '--check-only', *locations) session.run("isort", "--check-only", *locations)
# TODO: Include `mypy` once it passes # TODO: Include `mypy` once it passes
# - Only for the *.py files to be packaged # - Only for the *.py files to be packaged
@ -209,7 +222,7 @@ def lint_code(session: Session) -> None:
# session.run('mypy', PACKAGE_LOCATION) # 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: def test_code(session: Session) -> None:
"""Run the unit and integration tests with `pytest`. """Run the unit and integration tests with `pytest`.
@ -222,32 +235,32 @@ def test_code(session: Session) -> None:
install_pinned( install_pinned(
session, session,
# The tests import `velofy`, so it and its dependencies must be installed # The tests import `velofy`, so it and its dependencies must be installed
'.', # => A non-editable copy as it would really be installed ".", # => A non-editable copy as it would really be installed
'factory-boy', "factory-boy",
'Faker', "Faker",
'packaging', "packaging",
'pytest', "pytest",
'pytest-cov', "pytest-cov",
'pytest-env', "pytest-env",
'pytest-mock', "pytest-mock",
) )
session.run('pytest', '--version') session.run("pytest", "--version")
pytest_default_args = ( pytest_default_args = (
# See "[tool.coverage]" in pyproject.toml for `coverage` settings, # See "[tool.coverage]" in pyproject.toml for `coverage` settings,
# for example, branch coverage and report format, # for example, branch coverage and report format,
# and "[tool.coverage.paths]" mapping `coverage` to src/ # and "[tool.coverage.paths]" mapping `coverage` to src/
'--cov', "--cov",
'--no-cov-on-fail', "--no-cov-on-fail",
'--cov-fail-under=100', "--cov-fail-under=100",
TESTS_LOCATION, 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: def test_docstrings(session: Session) -> None:
"""Test the code snippets in the docstrings with `xdoctest`. """Test the code snippets in the docstrings with `xdoctest`.
@ -257,22 +270,22 @@ def test_docstrings(session: Session) -> None:
""" """
start(session) start(session)
install_pinned(session, '.', 'xdoctest[colors]') install_pinned(session, ".", "xdoctest[colors]")
# As `pytest-env` does for `pytest`, # As `pytest-env` does for `pytest`,
# keep `velofy` from connecting to the production database # keep `velofy` from connecting to the production database
session.env['TESTING'] = 'true' session.env["TESTING"] = "true"
session.run( session.run(
'python', "python",
'-m', "-m",
'xdoctest', "xdoctest",
PACKAGE, 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: def build_docs(session: Session) -> None:
"""Build the documentation with `sphinx`. """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 # The `sphinx-autodoc` extension imports `velofy` to read the docstrings
# => `velofy` and its dependencies must be installed # => `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`, # As `pytest-env` does for `pytest`,
# keep `velofy` from connecting to the production database # 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 # 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: def create_develop_environment(session: Session) -> None:
"""Set up the local develop environment in ".venv". """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 Then, `uv run` only uses that environment
with "UV_PROJECT_ENVIRONMENT" set to the same location. 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: 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'" # All dependency groups are installed because of "default-groups = 'all'"
# in the "[tool.uv]" section in pyproject.toml # in the "[tool.uv]" section in pyproject.toml
session.run( session.run(
'uv', "uv",
'sync', "sync",
'--all-extras', "--all-extras",
'--locked', "--locked",
env={'UV_PROJECT_ENVIRONMENT': location}, env={"UV_PROJECT_ENVIRONMENT": location},
external=True, 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: def audit_pinned_dependencies(session: Session) -> None:
"""Check dependencies for vulnerabilities with `pip-audit`. """Check dependencies for vulnerabilities with `pip-audit`.
@ -341,36 +354,36 @@ def audit_pinned_dependencies(session: Session) -> None:
start(session) start(session)
# `pip-audit` is not pinned to always check with its latest version # `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( session.run(
'uv', "uv",
'export', "export",
'--all-extras', "--all-extras",
'--all-groups', "--all-groups",
'--locked', "--locked",
'--no-emit-project', "--no-emit-project",
'--quiet', "--quiet",
f'--output-file={requirements_txt.name}', f"--output-file={requirements_txt.name}",
) )
session.run('pip-audit', '--version') session.run("pip-audit", "--version")
session.run( session.run(
'pip-audit', "pip-audit",
'--cache-dir=.cache/pip-audit', "--cache-dir=.cache/pip-audit",
'--disable-pip', "--disable-pip",
'--progress-spinner=off', "--progress-spinner=off",
f'--requirement={requirements_txt.name}', f"--requirement={requirements_txt.name}",
'--strict', "--strict",
# TODO: Remove these ignores once we upgrade to `black` v26 # TODO: Remove these ignores once we upgrade to `black` v26
'--ignore-vuln=PYSEC-2026-2120', "--ignore-vuln=PYSEC-2026-2120",
'--ignore-vuln=PYSEC-2026-2121', "--ignore-vuln=PYSEC-2026-2121",
'--ignore-vuln=CVE-2026-114134', "--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: def lock_dependencies(session: Session) -> None:
"""Lock dependencies in pyproject.toml into uv.lock. """Lock dependencies in pyproject.toml into uv.lock.
@ -385,12 +398,12 @@ def lock_dependencies(session: Session) -> None:
# and call `upgrade_dependencies()` directly # and call `upgrade_dependencies()` directly
# because `session.notify()` starts sessions with a new # because `session.notify()` starts sessions with a new
# `nox.Session` object that does not have the flag set # `nox.Session` object that does not have the flag set
session.env['_lock_only'] = 'true' session.env["_lock_only"] = "true"
upgrade_dependencies(session) 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: def upgrade_dependencies(session: Session) -> None:
"""Pin dependencies in uv.lock to their latest MINOR/PATCH versions. """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 So, the obtained upgrades must still be manually
`git commit`ed into the repository. `git commit`ed into the repository.
""" """
if session.env.get('_lock_only'): if session.env.get("_lock_only"):
upgrade = [] upgrade = []
elif session.posargs: 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: else:
upgrade = ['--upgrade'] upgrade = ["--upgrade"]
session.run('uv', '--version', external=True) session.run("uv", "--version", external=True)
session.run('uv', 'lock', *upgrade, 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: def check_dependency_upgrades(session: Session) -> None:
"""Check the dependencies in uv.lock for upgrades. """Check the dependencies in uv.lock for upgrades.
@ -438,17 +451,26 @@ def check_dependency_upgrades(session: Session) -> None:
start(session) start(session)
# The script only uses the standard library => Nothing to install # 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: 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" # .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: def clean_cwd(session: Session) -> None:
"""Remove (almost) all glob patterns listed in git's ignore file. """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_accept_arguments(session)
do_not_remove = { do_not_remove = {
'.env', ".env",
'.envrc', ".envrc",
'.python-version', ".python-version",
'.venv', ".venv",
} }
with pathlib.Path('.gitignore').open() as fp: with pathlib.Path(".gitignore").open() as fp:
ignored_patterns = { 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: with pathlib.Path(".gitignore").open() as fp:
excluded_patterns = {pattern[1:] for pattern in fp if pattern.startswith('!')} excluded_patterns = {pattern[1:] for pattern in fp if pattern.startswith("!")}
# Paths are resolved into absolute ones to avoid accidental matches # Paths are resolved into absolute ones to avoid accidental matches
excluded_paths = { 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 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` # The `path` must not be a sub-path of an `excluded_path`
if {path, *path.parents} & excluded_paths: if {path, *path.parents} & excluded_paths:
continue continue
session.run('rm', '-rf', path) session.run("rm", "-rf", path)
def _expand(*patterns: str) -> Generator[pathlib.Path, None, None]: 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 "--"' msg = 'be run without any positional arguments behind the "--"'
if raise_error: if raise_error:
session.error(f'Must {msg}') session.error(f"Must {msg}")
else: else:
session.warn(f'Should {msg}') session.warn(f"Should {msg}")
def do_not_reuse(session: Session, *, raise_error: bool = True) -> None: 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' msg = 'be run without the "-r" and "-R" flags'
if raise_error: if raise_error:
session.error(f'Must {msg}') session.error(f"Must {msg}")
else: else:
session.warn(f'Should {msg}') session.warn(f"Should {msg}")
def start(session: Session) -> None: def start(session: Session) -> None:
"""Show generic info about a session.""" """Show generic info about a session."""
if session.posargs: 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", "--version")
session.run('python', '-c', 'import sys; print(sys.executable)') session.run("python", "-c", "import sys; print(sys.executable)")
session.run('python', '-c', 'import sys; print(sys.path)') 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.getcwd())")
session.run('python', '-c', 'import os; print(os.environ["PATH"])') 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( session.run(
'mkdir', "mkdir",
'-p', "-p",
*( *(
f'.cache/{dir_}' f".cache/{dir_}"
for dir_ in ( for dir_ in (
'black', "black",
'coverage', "coverage",
'mypy', "mypy",
'nox', "nox",
'pytest', "pytest",
'tmp', "tmp",
) )
), ),
external=True, external=True,
@ -583,20 +605,20 @@ def install_pinned(
if skip_install(session): if skip_install(session):
return return
with tempfile.NamedTemporaryFile(suffix='.txt') as constraints_txt: with tempfile.NamedTemporaryFile(suffix=".txt") as constraints_txt:
session.run( session.run(
'uv', "uv",
'export', "export",
'--all-extras', "--all-extras",
'--all-groups', "--all-groups",
'--locked', "--locked",
'--no-emit-project', "--no-emit-project",
'--no-hashes', "--no-hashes",
'--quiet', "--quiet",
f'--output-file={constraints_txt.name}', f"--output-file={constraints_txt.name}",
) )
session.install( session.install(
f'--constraint={constraints_txt.name}', f"--constraint={constraints_txt.name}",
*packages_or_pip_args, *packages_or_pip_args,
**kwargs, **kwargs,
) )
@ -616,5 +638,5 @@ def skip_install(session: Session) -> bool:
if MAIN_PYTHON not in SUPPORTED_PYTHONS: 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) raise RuntimeError(msg)

View file

@ -91,10 +91,23 @@ dev = [
# Code Analyzers # Code Analyzers
"flake8 (>=7.5.0,<8.0.0)", "flake8 (>=7.5.0,<8.0.0)",
"flake8-annotations (>=3.3.1,<4.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-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-pyproject (>=1.2.4,<2.0.0)",
"flake8-pytest-style (>=2.2.0,<3.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)", "mypy (>=2.4.1,<3.0.0)",
"pep8-naming (>=0.15.1,<0.16.0)",
"pydoclint[flake8] (>=0.12.0,<0.13.0)",
] ]
test = [ test = [
@ -134,8 +147,6 @@ target-version = ["py313"]
line-length = 88 line-length = 88
skip-string-normalization = true # `wemake-python-styleguide` enforces single quotes
[tool.coverage] [tool.coverage]
@ -183,15 +194,15 @@ select = [
"E", "W", "E", "W",
# pyflakes => basic errors # pyflakes => basic errors
"F4", "F5", "F6", "F7", "F8", "F9", "F4", "F5", "F6", "F7", "F8", "F9",
# ======================== # =======
# wemake-python-styleguide # plugins
# Source: https://wemake-python-stylegui.de/en/latest/pages/usage/violations/index.html # =======
# ======================== # flake8-annotations => enforce type checking for functions
"WPS1", "WPS2", "WPS3", "WPS4", "WPS5", "WPS6", "ANN0", "ANN2", "ANN3",
# darglint => docstring matches implementation
"DAR0", "DAR1", "DAR2", "DAR3", "DAR4", "DAR5",
# flake8-bandit => common security issues # flake8-bandit => common security issues
"S1", "S2", "S3", "S4", "S5", "S6", "S7", "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 # flake8-broken-line => no \ to end a line
"N400", "N400",
# flake8-bugbear => opinionated bugs and design flaws # flake8-bugbear => opinionated bugs and design flaws
@ -204,27 +215,20 @@ select = [
"T100", "T100",
# flake8-docstrings => PEP257 compliance # flake8-docstrings => PEP257 compliance
"D1", "D2", "D3", "D4", "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 # flake8-pytest-style => enforce a consistent style with pytest
"PT0", "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. # By default, flake8 ignores some errors.
@ -234,96 +238,36 @@ ignore = []
# If --ignore is passed on the command # If --ignore is passed on the command
# line, still ignore the following: # line, still ignore the following:
extend-ignore = [ 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. # Too long line => duplicate with E501.
"B950", "B950",
# PEP 257 documents the arguments of `__init__()` in its own docstring.
"DOC301",
# Comply with black's style. # Comply with black's style.
# Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8 # 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`. # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`.
"PT023", "PT023",
# Google's Python Style Guide is not reStructuredText # Allow f-strings as the only type of string formatting.
# until after being processed by Sphinx Napoleon. "SFS301",
# Source: https://github.com/peterjc/flake8-rst-docstrings/issues/17 # TODOs need neither an author nor an issue.
"RST201", "RST203", "RST210", "RST213", "RST301", "T002", "T003",
# 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",
] ]
per-file-ignores = [ per-file-ignores = [
# Top-levels of a sub-packages are intended to import a lot. # Top-levels of a sub-packages are intended to import a lot.
"**/__init__.py:F401,WPS201", "**/__init__.py:F401",
# Allow shadowing built-ins and reading __*__ variables.
"docs/conf.py:WPS125,WPS609",
# Type annotations are not strictly enforced. # Type annotations are not strictly enforced.
"migrations/env.py:ANN0,ANN2", "migrations/env.py:ANN0,ANN2",
# - ANN0, ANN2 => Type annotations are not strictly enforced. # - ANN0, ANN2 => Type annotations are not strictly enforced.
# - S608 => Do not worry about SQL injection here. # - S608 => Do not worry about SQL injection here.
# - WPS114, WPS118 => File names of revisions are ok. "migrations/versions/*.py:ANN0,ANN2,S608",
# - WPS204, WPS213 => Revisions may have too many expressions. # Type annotations are not strictly enforced.
"migrations/versions/*.py:ANN0,ANN2,S608,WPS114,WPS118,WPS204,WPS213", "noxfile.py:ANN0,ANN2",
# - ANN0, ANN2 => Type annotations are not strictly enforced. # - ANN0, ANN2, DOC106, DOC107 => 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.
# - D106 => The `Meta` class inside the factory_boy models do not need a docstring. # - D106 => The `Meta` class inside the factory_boy models do not need a docstring.
# - S101 => `assert` statements are ok in the test suite. # - S101 => `assert` statements are ok in the test suite.
# - S311 => The `random` module is not used for cryptography. # - S311 => The `random` module is not used for cryptography.
# - WPS442 => Shadowing outer scopes occurs naturally with mocks. "tests/*.py:ANN0,ANN2,D106,DOC106,DOC107,S101,S311",
# - 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",
] ]
# Explicitly set mccabe's maximum complexity to 10 as recommended by # 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 # Source: https://en.wikipedia.org/wiki/Cyclomatic_complexity#Limiting_complexity_during_development
max-complexity = 10 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. # Comply with black's style.
# Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length # Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length
max-line-length = 88 max-line-length = 88
@ -344,24 +282,21 @@ max-line-length = 88
# Preview the code lines that cause errors. # Preview the code lines that cause errors.
show-source = true show-source = true
# =================================== # pydoclint
# wemake-python-styleguide's settings style = "google"
# =================================== arg-type-hints-in-docstring = false
allowed-domain-names = [ check-return-types = false
"data", check-yield-types = false
"obj",
"param",
"result",
"results",
"value",
]
max-name-length = 40
# darglint
strictness = "long"
# flake8-docstrings # flake8-docstrings
docstring-convention = "google" docstring-convention = "google"
# flake8-eradicate # flake8-quotes
eradicate-aggressive = true # 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 # flake8-pytest-style's settings

View file

@ -19,11 +19,11 @@ try:
_pkg_info = _metadata.metadata(__name__) _pkg_info = _metadata.metadata(__name__)
except _metadata.PackageNotFoundError: # pragma: no cover except _metadata.PackageNotFoundError: # pragma: no cover
__author__ = 'unknown' __author__ = "unknown"
__pkg_name__ = 'unknown' __pkg_name__ = "unknown"
__version__ = 'unknown' __version__ = "unknown"
else: else:
__author__ = _pkg_info['author'] __author__ = _pkg_info["author"]
__pkg_name__ = _pkg_info['name'] __pkg_name__ = _pkg_info["name"]
__version__ = _pkg_info['version'] __version__ = _pkg_info["version"]

View file

@ -16,11 +16,9 @@ import warnings
def random_schema_name() -> str: def random_schema_name() -> str:
"""Generate a random PostgreSQL schema name for testing.""" """Generate a random PostgreSQL schema name for testing."""
return 'temp_{name}'.format( letters = (random.choice(string.ascii_lowercase) for _ in range(10)) # noqa:S311
name=''.join( name = "".join(letters)
(random.choice(string.ascii_lowercase) for _ in range(10)), # noqa:S311 return f"temp_{name}"
),
)
class Config: class Config:
@ -54,33 +52,33 @@ class Config:
TRAIN_HORIZONS = [7, 8] TRAIN_HORIZONS = [7, 8]
# The demand forecasting methods used in the simulations. # The demand forecasting methods used in the simulations.
FORECASTING_METHODS = ['hets', 'rtarima'] FORECASTING_METHODS = ["hets", "rtarima"]
# Colors for the visualizations ins `folium`. # Colors for the visualizations ins `folium`.
RESTAURANT_COLOR = 'red' RESTAURANT_COLOR = "red"
CUSTOMER_COLOR = 'blue' CUSTOMER_COLOR = "blue"
NEUTRAL_COLOR = 'black' NEUTRAL_COLOR = "black"
# Implementation-specific settings # Implementation-specific settings
# -------------------------------- # --------------------------------
DATABASE_URI = os.getenv('DATABASE_URI') DATABASE_URI = os.getenv("DATABASE_URI")
GOOGLE_MAPS_API_KEY = os.getenv('GOOGLE_MAPS_API_KEY') GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY")
# The PostgreSQL schema that holds the tables with the original data. # 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. # 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 = "alembic_version"
ALEMBIC_TABLE_SCHEMA = 'public' ALEMBIC_TABLE_SCHEMA = "public"
R_LIBS_PATH = os.getenv('R_LIBS') R_LIBS_PATH = os.getenv("R_LIBS")
def __repr__(self) -> str: def __repr__(self) -> str:
"""Non-literal text representation.""" """Non-literal text representation."""
return '<configuration>' return "<configuration>"
class ProductionConfig(Config): class ProductionConfig(Config):
@ -94,11 +92,11 @@ class TestingConfig(Config):
TESTING = True TESTING = True
DATABASE_URI = os.getenv('DATABASE_URI_TESTING') or Config.DATABASE_URI DATABASE_URI = os.getenv("DATABASE_URI_TESTING") or Config.DATABASE_URI
CLEAN_SCHEMA = os.getenv('CLEAN_SCHEMA_TESTING') or random_schema_name() 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. """Create a new `Config` object.
Args: Args:
@ -109,12 +107,12 @@ def make_config(env: str = 'production') -> Config:
Raises: Raises:
ValueError: if `env` is not as specified ValueError: if `env` is not as specified
""" # noqa:DAR203 """
config: Config # otherwise mypy is confused config: Config # otherwise mypy is confused
if env.strip().lower() == 'production': if env.strip().lower() == "production":
config = ProductionConfig() config = ProductionConfig()
elif env.strip().lower() == 'testing': elif env.strip().lower() == "testing":
config = TestingConfig() config = TestingConfig()
else: else:
raise ValueError("Must be either 'production' or 'testing'") 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, # As pytest sets the "TESTING" environment variable explicitly,
# the warning is only emitted if the code is not run by pytest. # the warning is only emitted if the code is not run by pytest.
# We see the bad configuration immediately as all "db" tests fail. # We see the bad configuration immediately as all "db" tests fail.
if config.DATABASE_URI is None and not os.getenv('TESTING'): if config.DATABASE_URI is None and not os.getenv("TESTING"):
warnings.warn('Bad configuration: no DATABASE_URI set in the environment') warnings.warn(
"Bad configuration: no DATABASE_URI set in the environment",
stacklevel=2,
)
# Some functionalities require R and some packages installed. # Some functionalities require R and some packages installed.
# To ensure isolation and reproducibility, the projects keeps the R dependencies # To ensure isolation and reproducibility, the projects keeps the R dependencies
# in a project-local folder that must be set in the environment. # in a project-local folder that must be set in the environment.
if config.R_LIBS_PATH is None and not os.getenv('TESTING'): if config.R_LIBS_PATH is None and not os.getenv("TESTING"):
warnings.warn('Bad configuration: no R_LIBS set in the environment') warnings.warn(
"Bad configuration: no R_LIBS set in the environment",
stacklevel=2,
)
return config return config
config = make_config('testing' if os.getenv('TESTING') else 'production') config = make_config("testing" if os.getenv("TESTING") else "production")

View file

@ -7,5 +7,5 @@ from velofy.console import main
cli = main.entry_point 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) cli.add_command(gridify.gridify)

View file

@ -16,19 +16,19 @@ def db_revision(
def decorator(func: Callable[..., Any]) -> Callable[..., Any]: def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(func) @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.""" """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 result = subprocess.run( # noqa:S603,S607
['alembic', 'current'], ["alembic", "current"],
capture_output=True, capture_output=True,
check=False, check=False,
encoding='utf8', encoding="utf8",
) )
if not result.stdout.startswith(rev): if not result.stdout.startswith(rev):
click.echo( 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) sys.exit(1)

View file

@ -19,12 +19,12 @@ from velofy.forecasts import timify
@click.command() @click.command()
@click.argument('city', default='Paris', type=str) @click.argument("city", default="Paris", type=str)
@click.argument('side_length', default=1000, type=int) @click.argument("side_length", default=1000, type=int)
@click.argument('time_step', default=60, type=int) @click.argument("time_step", default=60, type=int)
@click.argument('train_horizon', default=8, type=int) @click.argument("train_horizon", default=8, type=int)
@decorators.db_revision('8bfb928a31f8') @decorators.db_revision("8bfb928a31f8")
def tactical_heuristic( # noqa:C901,WPS213,WPS216 def tactical_heuristic( # noqa:C901,DOC001
city: str, city: str,
side_length: int, side_length: int,
time_step: 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` TIME_STEP: length of one time step in minutes; defaults to `60`
TRAIN_HORIZON: length of the training horizon; defaults to `8` TRAIN_HORIZON: length of the training horizon; defaults to `8`
""" # noqa:D412,D417,RST215 """ # noqa:D412,D417 => formatted as `click` help text
# Input validation. # Input validation.
try: try:
city_obj = ( city_obj = db.session.query(db.City).filter_by(name=city.title()).one()
db.session.query(db.City).filter_by(name=city.title()).one() # noqa:WPS221
)
except orm_exc.NoResultFound: except orm_exc.NoResultFound:
click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"') click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"')
sys.exit(1) sys.exit(1)
@ -79,35 +77,35 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216
if grid.side_length == side_length: if grid.side_length == side_length:
break break
else: 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) sys.exit(1)
if time_step not in config.TIME_STEPS: 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) sys.exit(1)
if train_horizon not in config.TRAIN_HORIZONS: 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) sys.exit(1)
click.echo( click.echo(
'Parameters: ' "Parameters: "
+ f'city="{city}", grid.side_length={side_length}, ' + f"city={city}, grid.side_length={side_length}, "
+ f'time_step={time_step}, train_horizon={train_horizon}', + f"time_step={time_step}, train_horizon={train_horizon}",
) )
# Load the historic order data. # 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() order_history.aggregate_orders()
# Run the tactical heuristic. # 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 # Important: this check may need to be adapted once further
# commands are added the make `Forecast`s without the heuristic! # commands are added the make `Forecast`s without the heuristic!
# Continue with forecasting on the day the last prediction was made ... # Continue with forecasting on the day the last prediction was made ...
last_predict_at = ( 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.Pixel, db.Forecast.pixel_id == db.Pixel.id)
.join(db.Grid, db.Pixel.grid_id == db.Grid.id) .join(db.Grid, db.Pixel.grid_id == db.Grid.id)
.filter(db.Forecast.pixel == pixel) .filter(db.Forecast.pixel == pixel)
@ -133,8 +131,8 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216
train_horizon=train_horizon, train_horizon=train_horizon,
) )
click.echo( click.echo(
f'Predicting pixel #{pixel.id} in {city} ' f"Predicting pixel #{pixel.id} in {city} "
+ f'for {predict_day} with {model.name}', + f"for {predict_day} with {model.name}",
) )
# Only loop over the time steps corresponding to working hours. # Only loop over the time steps corresponding to working hours.

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