From 9fcb3c8c149f5088acf328e33655a5cdd7a16f4e Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Sat, 28 Nov 2026 02:01:12 +0100 Subject: [PATCH] Remove all "WPS" codes --- migrations/env.py | 4 +- ...806_23_f11cd76d2f45_create_the_database.py | 10 +- ...ame_training_horizon_into_train_horizon.py | 4 +- ...914_13_81aa304d7a6e_add_simulation_data.py | 12 +-- noxfile.py | 2 +- pyproject.toml | 95 ++----------------- src/velofy/console/decorators.py | 2 +- src/velofy/console/forecasts.py | 12 +-- src/velofy/console/main.py | 4 +- src/velofy/db/addresses.py | 8 +- src/velofy/db/addresses_addresses.py | 20 ++-- src/velofy/db/cities.py | 16 ++-- src/velofy/db/couriers.py | 2 +- src/velofy/db/customers.py | 28 +++--- src/velofy/db/forecasts.py | 4 +- src/velofy/db/grids.py | 6 +- src/velofy/db/meta.py | 10 +- src/velofy/db/orders.py | 6 +- src/velofy/db/pixels.py | 10 +- src/velofy/db/replay/simulations.py | 2 +- src/velofy/db/restaurants.py | 6 +- src/velofy/db/utils/colors.py | 2 +- src/velofy/db/utils/locations.py | 8 +- src/velofy/forecasts/methods/arima.py | 2 +- src/velofy/forecasts/methods/decomposition.py | 8 +- src/velofy/forecasts/methods/ets.py | 2 +- src/velofy/forecasts/models/base.py | 4 +- .../forecasts/models/tactical/horizontal.py | 2 +- .../forecasts/models/tactical/realtime.py | 2 +- .../forecasts/models/tactical/vertical.py | 2 +- src/velofy/forecasts/timify.py | 12 +-- src/velofy/init_r.py | 2 +- tests/console/test_gridify.py | 2 +- tests/db/fake_data/factories/addresses.py | 2 +- tests/db/fake_data/factories/couriers.py | 2 +- tests/db/fake_data/factories/customers.py | 2 +- tests/db/fake_data/factories/orders/ad_hoc.py | 6 +- tests/db/fake_data/factories/restaurants.py | 2 +- tests/db/fake_data/factories/utils.py | 2 +- tests/db/test_addresses_addresses.py | 4 +- tests/db/test_forecasts.py | 8 +- tests/db/test_grids.py | 10 +- tests/db/test_orders.py | 16 ++-- tests/db/test_pixels.py | 2 +- tests/db/utils/test_locations.py | 2 +- tests/forecasts/methods/test_decomposition.py | 6 +- tests/forecasts/test_models.py | 4 +- .../forecasts/timify/test_aggregate_orders.py | 24 ++--- .../forecasts/timify/test_make_time_series.py | 6 +- tests/test_config.py | 8 +- tests/test_init_r.py | 2 +- tests/test_version.py | 6 +- 52 files changed, 171 insertions(+), 254 deletions(-) diff --git a/migrations/env.py b/migrations/env.py index c93f08f..40e1288 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -21,9 +21,9 @@ log_config.fileConfig(context.config.config_file_name) def include_object(obj, _name, type_, _reflected, _compare_to): """Only include the clean schema into --autogenerate migrations.""" - if ( # noqa:WPS337 + if ( 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 ): return False diff --git a/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py b/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py index 9d77f3e..657045b 100644 --- a/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py +++ b/migrations/versions/rev_20200806_23_f11cd76d2f45_create_the_database.py @@ -38,7 +38,7 @@ def upgrade(): sa.Column('initial_zoom', sa.SmallInteger(), nullable=False), sa.PrimaryKeyConstraint('id', name=op.f('pk_cities')), *( - [ # noqa:WPS504 + [ sa.ForeignKeyConstraint( ['id'], [f'{config.ORIGINAL_SCHEMA}.cities.id'], @@ -83,7 +83,7 @@ def upgrade(): ), sa.PrimaryKeyConstraint('id', name=op.f('pk_couriers')), *( - [ # noqa:WPS504 + [ sa.ForeignKeyConstraint( ['id'], [f'{config.ORIGINAL_SCHEMA}.couriers.id'], @@ -148,7 +148,7 @@ def upgrade(): ), sa.PrimaryKeyConstraint('id', name=op.f('pk_addresses')), *( - [ # noqa:WPS504 + [ sa.ForeignKeyConstraint( ['id'], [f'{config.ORIGINAL_SCHEMA}.addresses.id'], @@ -210,7 +210,7 @@ def upgrade(): ), sa.PrimaryKeyConstraint('id', name=op.f('pk_restaurants')), *( - [ # noqa:WPS504 + [ sa.ForeignKeyConstraint( ['id'], [f'{config.ORIGINAL_SCHEMA}.businesses.id'], @@ -628,7 +628,7 @@ def upgrade(): ), sa.PrimaryKeyConstraint('id', name=op.f('pk_orders')), *( - [ # noqa:WPS504 + [ sa.ForeignKeyConstraint( ['id'], [f'{config.ORIGINAL_SCHEMA}.orders.id'], diff --git a/migrations/versions/rev_20210202_12_8bfb928a31f8_rename_training_horizon_into_train_horizon.py b/migrations/versions/rev_20210202_12_8bfb928a31f8_rename_training_horizon_into_train_horizon.py index 14ba4ae..a060a88 100644 --- a/migrations/versions/rev_20210202_12_8bfb928a31f8_rename_training_horizon_into_train_horizon.py +++ b/migrations/versions/rev_20210202_12_8bfb928a31f8_rename_training_horizon_into_train_horizon.py @@ -31,7 +31,7 @@ def upgrade(): TO train_horizon; """, - ) # noqa:WPS355 + ) def downgrade(): @@ -45,4 +45,4 @@ def downgrade(): TO training_horizon; """, - ) # noqa:WPS355 + ) diff --git a/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py b/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py index a59472f..d448e9f 100644 --- a/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py +++ b/migrations/versions/rev_20210914_13_81aa304d7a6e_add_simulation_data.py @@ -29,7 +29,7 @@ def upgrade(): ALTER TABLE {config.CLEAN_SCHEMA}.orders DROP CONSTRAINT ck_orders_on_ordered_timestamps_21; """, - ) # noqa:WPS355 + ) # Add forgotten check constraints to the `orders` table. op.execute( @@ -38,7 +38,7 @@ def upgrade(): ADD CONSTRAINT check_orders_on_ordered_timestamps_placed_at_before_pickup_at CHECK (placed_at < pickup_at); """, - ) # noqa:WPS355 + ) op.execute( f""" ALTER TABLE {config.CLEAN_SCHEMA}.orders @@ -55,7 +55,7 @@ def upgrade(): ) ); """, - ) # noqa:WPS355 + ) # This `UniqueConstraint` is needed by the `replayed_orders` table below. op.create_unique_constraint( @@ -403,17 +403,17 @@ def downgrade(): ALTER TABLE {config.CLEAN_SCHEMA}.orders DROP CONSTRAINT check_orders_on_scheduled_orders_must_be_at_quarters_of_an_hour; """, - ) # noqa:WPS355 + ) op.execute( f""" ALTER TABLE {config.CLEAN_SCHEMA}.orders DROP CONSTRAINT check_orders_on_ordered_timestamps_placed_at_before_pickup_at; """, - ) # noqa:WPS355 + ) op.execute( f""" ALTER TABLE {config.CLEAN_SCHEMA}.orders ADD CONSTRAINT ck_orders_on_ordered_timestamps_21 CHECK (cancelled_at > delivery_at); """, - ) # noqa:WPS355 + ) diff --git a/noxfile.py b/noxfile.py index 5889682..8cdb4fe 100644 --- a/noxfile.py +++ b/noxfile.py @@ -293,7 +293,7 @@ def build_docs(session: Session) -> None: # Verify that all external links return 200 OK 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') diff --git a/pyproject.toml b/pyproject.toml index 402c67a..1189072 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -187,7 +187,6 @@ select = [ # wemake-python-styleguide # Source: https://wemake-python-stylegui.de/en/latest/pages/usage/violations/index.html # ======================== - "WPS1", "WPS2", "WPS3", "WPS4", "WPS5", "WPS6", # darglint => docstring matches implementation "DAR0", "DAR1", "DAR2", "DAR3", "DAR4", "DAR5", # flake8-bandit => common security issues @@ -234,96 +233,36 @@ ignore = [] # If --ignore is passed on the command # line, still ignore the following: extend-ignore = [ - # TODO: New in `wemake-python-styleguide` v0.15 - v0.17, revisit in the tooling goal - "WPS110", - "WPS237", - "WPS238", - "WPS358", - "WPS456", - "WPS458", - "WPS459", - "WPS462", - "WPS469", # Too long line => duplicate with E501. "B950", # Comply with black's style. # Source: https://github.com/psf/black/blob/master/docs/compatible_configs.md#flake8 - "E203", "W503", "WPS348", + "E203", "W503", # Let's not do `@pytest.mark.no_cover()` instead of `@pytest.mark.no_cover`. "PT023", # Google's Python Style Guide is not reStructuredText # until after being processed by Sphinx Napoleon. # Source: https://github.com/peterjc/flake8-rst-docstrings/issues/17 "RST201", "RST203", "RST210", "RST213", "RST301", - # The "too deep nesting" violation fires off "too early" and cannot be configured. - "WPS220", - # String constant over-use is checked visually by the programmer. - "WPS226", - # Function complexity is checked by `mccabe` (=C901), - # which yields the same result in most cases. - "WPS231", - # Modules as a whole are assumed to be not "too complex". - "WPS232", - # Allow underscores in numbers. - "WPS303", - # f-strings are ok. - "WPS305", - # Classes should not have to specify a base class. - "WPS306", - # Let's be modern: The Walrus is ok. - "WPS332", - # Let's not worry about the number of noqa's. - # Multi-line loops are ok. - "WPS352", - "WPS402", - # Putting logic into __init__.py files may be justified. - "WPS412", - # Allow multiple assignment, e.g., x = y = 123 - "WPS429", - # There are no magic numbers. - "WPS432", ] per-file-ignores = [ # Top-levels of a sub-packages are intended to import a lot. - "**/__init__.py:F401,WPS201", - # Allow shadowing built-ins and reading __*__ variables. - "docs/conf.py:WPS125,WPS609", + "**/__init__.py:F401", # Type annotations are not strictly enforced. "migrations/env.py:ANN0,ANN2", # - ANN0, ANN2 => Type annotations are not strictly enforced. # - S608 => Do not worry about SQL injection here. - # - WPS114, WPS118 => File names of revisions are ok. - # - WPS204, WPS213 => Revisions may have too many expressions. - "migrations/versions/*.py:ANN0,ANN2,S608,WPS114,WPS118,WPS204,WPS213", - # - ANN0, ANN2 => Type annotations are not strictly enforced. - # - WPS202 => TODO (isort): Check if still too many module members. - # - WPS213 => TODO (isort): Remove after simplifying the nox session "lint". - "noxfile.py:ANN0,ANN2,WPS202,WPS213", - # Allow upper case class variables within classes. - "src/velofy/configuration.py:WPS115", - # The module does not have too many imports. - "src/velofy/db/addresses_addresses.py:WPS201", - # The many noqa's are ok. - "src/velofy/forecasts/models/tactical/horizontal.py:WPS403", - # - S608 => No SQL injection as the inputs come from a safe source. - # - WPS403 => The many noqa's are ok. - "src/velofy/forecasts/timify.py:S608,WPS403", + "migrations/versions/*.py:ANN0,ANN2,S608", + # Type annotations are not strictly enforced. + "noxfile.py:ANN0,ANN2", + # No SQL injection as the inputs come from a safe source. + "src/velofy/forecasts/timify.py:S608", # - ANN0, ANN2 => Type annotations are not strictly enforced. # - D106 => The `Meta` class inside the factory_boy models do not need a docstring. # - S101 => `assert` statements are ok in the test suite. # - S311 => The `random` module is not used for cryptography. - # - WPS442 => Shadowing outer scopes occurs naturally with mocks. - # - WPS100 => `utils` should be a valid module name. - # - WPS118 => Test names may be longer than 40 characters. - # - WPS202, WPS204, WPS214 => Modules may have many test cases. - # - WPS221 => Do not check for Jones complexity in the test suite. - # - WPS338 => "Private" methods are really just a convention for - # fixtures without a return value. - # - WPS402 => We do not care about the number of "# noqa"s in the test suite. - # - WPS430 => Allow closures. - # - WPS437 => When testing, it is normal to use implementation details. - "tests/*.py:ANN0,ANN2,D106,S101,S311,WPS442,WPS100,WPS118,WPS202,WPS204,WPS214,WPS221,WPS338,WPS402,WPS430,WPS437", + "tests/*.py:ANN0,ANN2,D106,S101,S311", ] # Explicitly set mccabe's maximum complexity to 10 as recommended by @@ -331,12 +270,6 @@ per-file-ignores = [ # Source: https://en.wikipedia.org/wiki/Cyclomatic_complexity#Limiting_complexity_during_development max-complexity = 10 -# Allow more than wemake-python-styleguide's 5 local variables per function. -max-local-variables = 8 - -# Allow more than wemake-python-styleguide's 7 methods per class. -max-methods = 15 - # Comply with black's style. # Source: https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length max-line-length = 88 @@ -344,18 +277,6 @@ max-line-length = 88 # Preview the code lines that cause errors. show-source = true -# =================================== -# wemake-python-styleguide's settings -# =================================== -allowed-domain-names = [ - "data", - "obj", - "param", - "result", - "results", - "value", -] -max-name-length = 40 # darglint strictness = "long" # flake8-docstrings diff --git a/src/velofy/console/decorators.py b/src/velofy/console/decorators.py index 74d3714..2a021cb 100644 --- a/src/velofy/console/decorators.py +++ b/src/velofy/console/decorators.py @@ -16,7 +16,7 @@ def db_revision( def decorator(func: Callable[..., Any]) -> Callable[..., Any]: @functools.wraps(func) - def ensure(*args: Any, **kwargs: Any) -> Any: # noqa:WPS430 + def ensure(*args: Any, **kwargs: Any) -> Any: """Do not execute the `func` if the revision does not match.""" if not os.getenv('TESTING'): result = subprocess.run( # noqa:S603,S607 diff --git a/src/velofy/console/forecasts.py b/src/velofy/console/forecasts.py index 91aa0db..0317ba9 100644 --- a/src/velofy/console/forecasts.py +++ b/src/velofy/console/forecasts.py @@ -24,7 +24,7 @@ from velofy.forecasts import timify @click.argument('time_step', default=60, type=int) @click.argument('train_horizon', default=8, type=int) @decorators.db_revision('8bfb928a31f8') -def tactical_heuristic( # noqa:C901,WPS213,WPS216 +def tactical_heuristic( # noqa:C901 city: str, side_length: int, time_step: int, @@ -68,9 +68,7 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216 # Input validation. try: - city_obj = ( - db.session.query(db.City).filter_by(name=city.title()).one() # noqa:WPS221 - ) + city_obj = db.session.query(db.City).filter_by(name=city.title()).one() except orm_exc.NoResultFound: click.echo('NAME must be one of "Paris", "Lyon", or "Bordeaux"') sys.exit(1) @@ -97,17 +95,17 @@ def tactical_heuristic( # noqa:C901,WPS213,WPS216 ) # Load the historic order data. - order_history = timify.OrderHistory(grid=grid, time_step=time_step) # noqa:WPS441 + order_history = timify.OrderHistory(grid=grid, time_step=time_step) order_history.aggregate_orders() # Run the tactical heuristic. - for pixel in grid.pixels: # noqa:WPS441 + for pixel in grid.pixels: # Important: this check may need to be adapted once further # commands are added the make `Forecast`s without the heuristic! # Continue with forecasting on the day the last prediction was made ... last_predict_at = ( - db.session.query(func.max(db.Forecast.start_at)) # noqa:WPS221 + db.session.query(func.max(db.Forecast.start_at)) .join(db.Pixel, db.Forecast.pixel_id == db.Pixel.id) .join(db.Grid, db.Pixel.grid_id == db.Grid.id) .filter(db.Forecast.pixel == pixel) diff --git a/src/velofy/console/main.py b/src/velofy/console/main.py index d4673dd..a9333d7 100644 --- a/src/velofy/console/main.py +++ b/src/velofy/console/main.py @@ -16,8 +16,8 @@ def show_version(ctx: cli_core.Context, _param: Any, value: bool) -> None: return # Mimic the colors of `poetry version`. - pkg_name = click.style(velofy.__pkg_name__, fg='green') # noqa:WPS609 - version = click.style(velofy.__version__, fg='blue') # noqa:WPS609 + pkg_name = click.style(velofy.__pkg_name__, fg='green') + version = click.style(velofy.__version__, fg='blue') # Include a warning for development versions. warning = click.style(' (development)', fg='red') if '.dev' in version else '' click.echo(f'{pkg_name}, version {version}{warning}') diff --git a/src/velofy/db/addresses.py b/src/velofy/db/addresses.py index 4fabcbc..9c237c4 100644 --- a/src/velofy/db/addresses.py +++ b/src/velofy/db/addresses.py @@ -22,7 +22,7 @@ class Address(meta.Base): __tablename__ = 'addresses' # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) primary_id = sa.Column(sa.Integer, nullable=False, index=True) created_at = sa.Column(sa.DateTime, nullable=False) place_id = sa.Column(sa.Unicode(length=120), nullable=False, index=True) @@ -116,7 +116,7 @@ class Address(meta.Base): return location @property - def x(self) -> int: # noqa=WPS111 + def x(self) -> int: """The relative x-coordinate within the `.city` in meters. On the implied x-y plane, the `.city`'s southwest corner is the origin. @@ -126,7 +126,7 @@ class Address(meta.Base): return self.location.x @property - def y(self) -> int: # noqa=WPS111 + def y(self) -> int: """The relative y-coordinate within the `.city` in meters. On the implied x-y plane, the `.city`'s southwest corner is the origin. @@ -145,7 +145,7 @@ class Address(meta.Base): return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `.city.map` object.""" return self.city.map diff --git a/src/velofy/db/addresses_addresses.py b/src/velofy/db/addresses_addresses.py index f7d6791..f6aef0b 100644 --- a/src/velofy/db/addresses_addresses.py +++ b/src/velofy/db/addresses_addresses.py @@ -128,9 +128,7 @@ class Path(meta.Base): # We consider all 2-tuples of `Address`es. The symmetric graph is ... for first, second in itertools.combinations(addresses, 2): # ... implicitly enforced by a precedence constraint for the `.id`s. - first, second = ( # noqa:WPS211 - (first, second) if first.id < second.id else (second, first) - ) + first, second = (first, second) if first.id < second.id else (second, first) # If there is no `Path` object in the database ... path = ( @@ -158,7 +156,7 @@ class Path(meta.Base): paths.append(path) if google_maps: - for path in paths: # noqa:WPS440 + for path in paths: path.sync_with_google_maps() return paths @@ -212,8 +210,8 @@ class Path(meta.Base): # Source: https://developers.google.com/maps/documentation/directions/get-directions#Legs # noqa:E501 route = response[0]['legs'][0] - self.bicycle_distance = route['distance']['value'] # noqa:WPS601 - self.bicycle_duration = route['duration']['value'] # noqa:WPS601 + self.bicycle_distance = route['distance']['value'] + self.bicycle_duration = route['duration']['value'] # Each route consists of many "steps" that are instructions as to how to # get from A to B. As a step's "start_location" may equal the previous step's @@ -221,23 +219,23 @@ class Path(meta.Base): # pairs that make up the path from `.first_address` to `.second_address`. steps: ordered_set.OrderedSet[Tuple[float, float]] = ordered_set.OrderedSet() for step in route['steps']: - steps.add( # noqa:WPS221 + steps.add( (step['start_location']['lat'], step['start_location']['lng']), ) - steps.add( # noqa:WPS221 + steps.add( (step['end_location']['lat'], step['end_location']['lng']), ) steps.discard(self.first_address.location.lat_lng) steps.discard(self.second_address.location.lat_lng) - self._directions = json.dumps(list(steps)) # noqa:WPS601 + self._directions = json.dumps(list(steps)) db.session.add(self) db.session.commit() @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Convenience property to obtain the underlying `City.map`.""" return self.first_address.city.map @@ -256,7 +254,7 @@ class Path(meta.Base): return points - def draw( # noqa:WPS211 + def draw( self, *, reverse: bool = False, diff --git a/src/velofy/db/cities.py b/src/velofy/db/cities.py index 8021b08..47d3a29 100644 --- a/src/velofy/db/cities.py +++ b/src/velofy/db/cities.py @@ -21,7 +21,7 @@ class City(meta.Base): __tablename__ = 'cities' # Generic columns - id = sa.Column( # noqa:WPS125 + id = sa.Column( sa.SmallInteger, primary_key=True, autoincrement=False, @@ -110,12 +110,12 @@ class City(meta.Base): return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """A `folium.Map` object aligned with the city's viewport. See docstring for `.clear_map()` for further info. """ - if not hasattr(self, '_map'): # noqa:WPS421 note:d334120e + if not hasattr(self, '_map'): # note:d334120e self.clear_map() return self._map @@ -137,7 +137,7 @@ class City(meta.Base): db.session.query(db.Address) .filter( db.Address.id.in_( - db.session.query(db.Address.primary_id) # noqa:WPS221 + db.session.query(db.Address.primary_id) .join(db.Restaurant, db.Address.id == db.Restaurant.address_id) .filter(db.Address.city == self) .distinct() @@ -157,9 +157,9 @@ class City(meta.Base): .all() ) if len(restaurants) == 1: - tooltip = f'{restaurants[0].name} (#{restaurants[0].id})' # noqa:WPS221 + tooltip = f'{restaurants[0].name} (#{restaurants[0].id})' else: - tooltip = 'Restaurants ' + ', '.join( # noqa:WPS336 + tooltip = 'Restaurants ' + ', '.join( f'#{restaurant.id}' for restaurant in restaurants ) @@ -183,7 +183,7 @@ class City(meta.Base): else: radius = 1 - tooltip += f' | n_orders={n_orders}' # noqa:WPS336 + tooltip += f' | n_orders={n_orders}' address.draw( radius=radius, @@ -239,7 +239,7 @@ class City(meta.Base): if not address.is_primary: continue - marker = folium.Circle( # noqa:WPS317 + marker = folium.Circle( (address.latitude, address.longitude), color=colors[address.zip_code], radius=1, diff --git a/src/velofy/db/couriers.py b/src/velofy/db/couriers.py index f6dfbe5..5ea42bc 100644 --- a/src/velofy/db/couriers.py +++ b/src/velofy/db/couriers.py @@ -13,7 +13,7 @@ class Courier(meta.Base): __tablename__ = 'couriers' # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) created_at = sa.Column(sa.DateTime, nullable=False) vehicle = sa.Column(sa.Unicode(length=10), nullable=False) historic_speed = sa.Column('speed', postgresql.DOUBLE_PRECISION, nullable=False) diff --git a/src/velofy/db/customers.py b/src/velofy/db/customers.py index 7afc468..72d165b 100644 --- a/src/velofy/db/customers.py +++ b/src/velofy/db/customers.py @@ -17,7 +17,7 @@ class Customer(meta.Base): __tablename__ = 'customers' # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) def __repr__(self) -> str: """Non-literal text representation.""" @@ -35,15 +35,15 @@ class Customer(meta.Base): Returns: self: enabling method chaining """ # noqa:D402,DAR203 - self.orders[0].pickup_address.city.clear_map() # noqa:WPS219 + self.orders[0].pickup_address.city.clear_map() return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `...city.map` object.""" - return self.orders[0].pickup_address.city.map # noqa:WPS219 + return self.orders[0].pickup_address.city.map - def draw( # noqa:C901,WPS210 + def draw( # noqa:C901 self, restaurants: bool = True, order_counts: bool = False, # pragma: no cover @@ -72,7 +72,7 @@ class Customer(meta.Base): db.Address.id.in_( row.primary_id for row in ( - db.session.query(db.Address.primary_id) # noqa:WPS221 + db.session.query(db.Address.primary_id) .join(db.Order, db.Address.id == db.Order.delivery_address_id) .filter(db.Order.customer_id == self.id) .distinct() @@ -122,7 +122,7 @@ class Customer(meta.Base): db.session.query(db.Address) .filter( db.Address.id.in_( - db.session.query(db.Address.primary_id) # noqa:WPS221 + db.session.query(db.Address.primary_id) .join(db.Order, db.Address.id == db.Order.pickup_address_id) .filter(db.Order.customer_id == self.id) .distinct() @@ -132,14 +132,14 @@ class Customer(meta.Base): .all() ) - for address in pickup_addresses: # noqa:WPS440 + for address in pickup_addresses: # Show the restaurant's name if there is only one. # Otherwise, list all the restaurants' ID's. # We cannot show the `Order.restaurant.name` due to the aggregation. restaurants = ( db.session.query(db.Restaurant) .join(db.Address, db.Restaurant.address_id == db.Address.id) - .filter(db.Address.primary_id == address.id) # noqa:WPS441 + .filter(db.Address.primary_id == address.id) .all() ) if len(restaurants) == 1: # type:ignore @@ -147,7 +147,7 @@ class Customer(meta.Base): f'{restaurants[0].name} (#{restaurants[0].id})' # type:ignore ) else: - tooltip = 'Restaurants ' + ', '.join( # noqa:WPS336 + tooltip = 'Restaurants ' + ', '.join( f'#{restaurant.id}' for restaurant in restaurants # type:ignore ) @@ -156,7 +156,7 @@ class Customer(meta.Base): db.session.query(db.Order) .join(db.Address, db.Order.pickup_address_id == db.Address.id) .filter(db.Order.customer_id == self.id) - .filter(db.Address.primary_id == address.id) # noqa:WPS441 + .filter(db.Address.primary_id == address.id) .count() ) if n_orders >= 25: @@ -170,9 +170,9 @@ class Customer(meta.Base): else: radius = 1 - tooltip += f' | n_orders={n_orders}' # noqa:WPS336 + tooltip += f' | n_orders={n_orders}' - address.draw( # noqa:WPS441 + address.draw( radius=radius, color=config.RESTAURANT_COLOR, fill_color=config.RESTAURANT_COLOR, @@ -181,7 +181,7 @@ class Customer(meta.Base): ) else: - address.draw( # noqa:WPS441 + address.draw( radius=1, color=config.RESTAURANT_COLOR, tooltip=tooltip, diff --git a/src/velofy/db/forecasts.py b/src/velofy/db/forecasts.py index 8f28899..5eeb500 100644 --- a/src/velofy/db/forecasts.py +++ b/src/velofy/db/forecasts.py @@ -23,7 +23,7 @@ class Forecast(meta.Base): __tablename__ = 'forecasts' # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) pixel_id = sa.Column(sa.Integer, nullable=False, index=True) start_at = sa.Column(sa.DateTime, nullable=False) time_step = sa.Column(sa.SmallInteger, nullable=False) @@ -151,7 +151,7 @@ class Forecast(meta.Base): ) @classmethod - def from_dataframe( # noqa:WPS210,WPS211 + def from_dataframe( cls, pixel: db.Pixel, time_step: int, diff --git a/src/velofy/db/grids.py b/src/velofy/db/grids.py index a77d4a2..df362eb 100644 --- a/src/velofy/db/grids.py +++ b/src/velofy/db/grids.py @@ -22,7 +22,7 @@ class Grid(meta.Base): __tablename__ = 'grids' # Columns - id = sa.Column( # noqa:WPS125 + id = sa.Column( sa.SmallInteger, primary_key=True, autoincrement=True, @@ -63,7 +63,7 @@ class Grid(meta.Base): return round((self.side_length**2) / 1_000_000, 1) @classmethod - def gridify(cls, city: db.City, side_length: int) -> db.Grid: # noqa:WPS210 + def gridify(cls, city: db.City, side_length: int) -> db.Grid: """Create a fully populated `Grid` for a `city`. The `Grid` contains only `Pixel`s that have at least one @@ -124,7 +124,7 @@ class Grid(meta.Base): return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `.city.map` object.""" return self.city.map diff --git a/src/velofy/db/meta.py b/src/velofy/db/meta.py index a9ddef1..b4e1506 100644 --- a/src/velofy/db/meta.py +++ b/src/velofy/db/meta.py @@ -12,11 +12,11 @@ Base: Any = orm.declarative_base( metadata=sa.MetaData( schema=velofy.config.CLEAN_SCHEMA, naming_convention={ - 'pk': 'pk_%(table_name)s', # noqa:WPS323 - 'fk': 'fk_%(table_name)s_to_%(referred_table_name)s_via_%(column_0_N_name)s', # noqa:E501,WPS323 - 'uq': 'uq_%(table_name)s_on_%(column_0_N_name)s', # noqa:WPS323 - 'ix': 'ix_%(table_name)s_on_%(column_0_N_name)s', # noqa:WPS323 - 'ck': 'ck_%(table_name)s_on_%(constraint_name)s', # noqa:WPS323 + 'pk': 'pk_%(table_name)s', + 'fk': 'fk_%(table_name)s_to_%(referred_table_name)s_via_%(column_0_N_name)s', # noqa:E501 + 'uq': 'uq_%(table_name)s_on_%(column_0_N_name)s', + 'ix': 'ix_%(table_name)s_on_%(column_0_N_name)s', + 'ck': 'ck_%(table_name)s_on_%(constraint_name)s', }, ), ) diff --git a/src/velofy/db/orders.py b/src/velofy/db/orders.py index f12bfa7..f0723d0 100644 --- a/src/velofy/db/orders.py +++ b/src/velofy/db/orders.py @@ -12,13 +12,13 @@ from velofy import db from velofy.db import meta -class Order(meta.Base): # noqa:WPS214 +class Order(meta.Base): """An order by a `Customer` of the UDP.""" __tablename__ = 'orders' # Generic columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=False) _delivery_id = sa.Column('delivery_id', sa.Integer, index=True, unique=True) customer_id = sa.Column(sa.Integer, nullable=False, index=True) placed_at = sa.Column(sa.DateTime, nullable=False, index=True) @@ -364,7 +364,7 @@ class Order(meta.Base): # noqa:WPS214 def corrected(self) -> bool: """If any timestamp was corrected as compared to the original data.""" return ( - self.scheduled_delivery_at_corrected # noqa:WPS222 => too much logic + self.scheduled_delivery_at_corrected # => too much logic or self.cancelled_at_corrected or self.restaurant_notified_at_corrected or self.restaurant_confirmed_at_corrected diff --git a/src/velofy/db/pixels.py b/src/velofy/db/pixels.py index a4a80ba..708e3e0 100644 --- a/src/velofy/db/pixels.py +++ b/src/velofy/db/pixels.py @@ -28,7 +28,7 @@ class Pixel(meta.Base): __tablename__ = 'pixels' # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) grid_id = sa.Column(sa.SmallInteger, nullable=False, index=True) n_x = sa.Column(sa.SmallInteger, nullable=False, index=True) n_y = sa.Column(sa.SmallInteger, nullable=False, index=True) @@ -141,11 +141,11 @@ class Pixel(meta.Base): return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `.city.map` object.""" return self.grid.city.map - def draw( # noqa:C901,WPS210 + def draw( # noqa:C901 self, restaurants: bool = True, order_counts: bool = False, # pragma: no cover @@ -223,7 +223,7 @@ class Pixel(meta.Base): f'{restaurants[0].name} (#{restaurants[0].id})' # type:ignore ) else: - tooltip = 'Restaurants ' + ', '.join( # noqa:WPS336 + tooltip = 'Restaurants ' + ', '.join( f'#{restaurant.id}' for restaurant in restaurants # type:ignore ) @@ -247,7 +247,7 @@ class Pixel(meta.Base): else: radius = 1 - tooltip += f' | n_orders={n_orders}' # noqa:WPS336 + tooltip += f' | n_orders={n_orders}' address.draw( radius=radius, diff --git a/src/velofy/db/replay/simulations.py b/src/velofy/db/replay/simulations.py index 88e3547..c8caf4f 100644 --- a/src/velofy/db/replay/simulations.py +++ b/src/velofy/db/replay/simulations.py @@ -15,7 +15,7 @@ class ReplaySimulation(meta.Base): __tablename__ = 'replay_simulations' # Columns - id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) # noqa:WPS125 + id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) city_id = sa.Column(sa.SmallInteger, nullable=False, index=True) strategy = sa.Column(sa.Unicode(length=100), nullable=False, index=True) # `.run` may be used as random seed. diff --git a/src/velofy/db/restaurants.py b/src/velofy/db/restaurants.py index 181b5ac..7e893e0 100644 --- a/src/velofy/db/restaurants.py +++ b/src/velofy/db/restaurants.py @@ -22,7 +22,7 @@ class Restaurant(meta.Base): __tablename__ = 'restaurants' # Columns - id = sa.Column( # noqa:WPS125 + id = sa.Column( sa.SmallInteger, primary_key=True, autoincrement=False, @@ -70,7 +70,7 @@ class Restaurant(meta.Base): return self @property # pragma: no cover - def map(self) -> folium.Map: # noqa:WPS125 + def map(self) -> folium.Map: """Shortcut to the `.address.city.map` object.""" return self.address.city.map @@ -100,7 +100,7 @@ class Restaurant(meta.Base): db.Address.id.in_( row.primary_id for row in ( - db.session.query(db.Address.primary_id) # noqa:WPS221 + db.session.query(db.Address.primary_id) .join( db.Order, db.Address.id == db.Order.delivery_address_id, diff --git a/src/velofy/db/utils/colors.py b/src/velofy/db/utils/colors.py index 02edaec..0d90181 100644 --- a/src/velofy/db/utils/colors.py +++ b/src/velofy/db/utils/colors.py @@ -69,4 +69,4 @@ def rgb_to_hex(*args: float) -> str: # pragma: no cover int(255 * args[1]), int(255 * args[2]), ) - return f'#{red:02x}{green:02x}{blue:02x}' # noqa:WPS221 + return f'#{red:02x}{green:02x}{blue:02x}' diff --git a/src/velofy/db/utils/locations.py b/src/velofy/db/utils/locations.py index a90fc97..4a04492 100644 --- a/src/velofy/db/utils/locations.py +++ b/src/velofy/db/utils/locations.py @@ -7,7 +7,7 @@ from typing import Optional, Tuple import utm -class Location: # noqa:WPS214 +class Location: """A location represented in WGS84 and UTM coordinates. WGS84: @@ -50,7 +50,7 @@ class Location: # noqa:WPS214 >>> Location(43.6532, -79.3832) """ - return f'' # noqa:WPS221 + return f'' @property def latitude(self) -> float: @@ -104,7 +104,7 @@ class Location: # noqa:WPS214 return (self.easting, self.northing) == (other.easting, other.northing) @property - def x(self) -> int: # noqa:WPS111 + def x(self) -> int: """The `.easting` of the location in meters, relative to some origin. The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`. @@ -115,7 +115,7 @@ class Location: # noqa:WPS214 return self._normalized_easting @property - def y(self) -> int: # noqa:WPS111 + def y(self) -> int: """The `.northing` of the location in meters, relative to some origin. The origin, which defines the `(0, 0)` coordinate, is set with `.relate_to()`. diff --git a/src/velofy/forecasts/methods/arima.py b/src/velofy/forecasts/methods/arima.py index 337527d..48849e3 100644 --- a/src/velofy/forecasts/methods/arima.py +++ b/src/velofy/forecasts/methods/arima.py @@ -33,7 +33,7 @@ def predict( """ # Initialize R only if it is actually used. # For example, the nox session "ci-tests-fast" does not use it. - from velofy import init_r # noqa:F401,WPS433 + from velofy import init_r # noqa:F401 # Re-seed R every time it is used to ensure reproducibility. robjects.r('set.seed(42)') diff --git a/src/velofy/forecasts/methods/decomposition.py b/src/velofy/forecasts/methods/decomposition.py index 36482af..ebcd5e3 100644 --- a/src/velofy/forecasts/methods/decomposition.py +++ b/src/velofy/forecasts/methods/decomposition.py @@ -12,7 +12,7 @@ from rpy2 import robjects from rpy2.robjects import pandas2ri -def stl( # noqa:C901,WPS210,WPS211 +def stl( # noqa:C901 time_series: pd.Series, *, frequency: int, @@ -26,7 +26,7 @@ def stl( # noqa:C901,WPS210,WPS211 jt: Optional[int] = None, jl: Optional[int] = None, ni: int = 2, - no: int = 0, # noqa:WPS110 + no: int = 0, ) -> pd.DataFrame: """Decompose a time series into seasonal, trend, and residual components. @@ -157,7 +157,7 @@ def stl( # noqa:C901,WPS210,WPS211 # Initialize R only if it is actually used. # For example, the nox session "ci-tests-fast" does not use it. - from velofy import init_r # noqa:F401,WPS433 + from velofy import init_r # noqa:F401 # Re-seed R every time it is used to ensure reproducibility. robjects.r('set.seed(42)') @@ -177,7 +177,7 @@ def stl( # noqa:C901,WPS210,WPS211 jl, robust, ni, - no, # noqa:WPS221 + no, ) # Unpack the result to a `pd.DataFrame`. diff --git a/src/velofy/forecasts/methods/ets.py b/src/velofy/forecasts/methods/ets.py index 6962f6f..0b21e83 100644 --- a/src/velofy/forecasts/methods/ets.py +++ b/src/velofy/forecasts/methods/ets.py @@ -34,7 +34,7 @@ def predict( """ # Initialize R only if it is actually used. # For example, the nox session "ci-tests-fast" does not use it. - from velofy import init_r # noqa:F401,WPS433 + from velofy import init_r # noqa:F401 # Re-seed R every time it is used to ensure reproducibility. robjects.r('set.seed(42)') diff --git a/src/velofy/forecasts/models/base.py b/src/velofy/forecasts/models/base.py index 7f98bf6..8eae03e 100644 --- a/src/velofy/forecasts/models/base.py +++ b/src/velofy/forecasts/models/base.py @@ -80,8 +80,8 @@ class ForecastingModelABC(abc.ABC): # noqa:DAR401 RuntimeError """ - if ( # noqa:WPS337 - cached_forecast := db.session.query(db.Forecast) # noqa:WPS221 + if ( + cached_forecast := db.session.query(db.Forecast) .filter_by(pixel=pixel) .filter_by(start_at=predict_at) .filter_by(time_step=self._order_history.time_step) diff --git a/src/velofy/forecasts/models/tactical/horizontal.py b/src/velofy/forecasts/models/tactical/horizontal.py index 9a4ab81..5b7b35c 100644 --- a/src/velofy/forecasts/models/tactical/horizontal.py +++ b/src/velofy/forecasts/models/tactical/horizontal.py @@ -129,7 +129,7 @@ class HorizontalSMAModel(base.ForecastingModelABC): ) # Sanity checks. - if ( # noqa:WPS337 + if ( predictions[['actual', 'prediction']].isnull().any().any() ): # pragma: no cover diff --git a/src/velofy/forecasts/models/tactical/realtime.py b/src/velofy/forecasts/models/tactical/realtime.py index 78933e8..082f7a6 100644 --- a/src/velofy/forecasts/models/tactical/realtime.py +++ b/src/velofy/forecasts/models/tactical/realtime.py @@ -88,7 +88,7 @@ class RealtimeARIMAModel(base.ForecastingModelABC): data={ 'actual': actuals_ts, 'prediction': ( - seasonal_predictions['prediction'] # noqa:WPS204 + seasonal_predictions['prediction'] + seasonally_adjusted_predictions['prediction'] ), 'low80': ( diff --git a/src/velofy/forecasts/models/tactical/vertical.py b/src/velofy/forecasts/models/tactical/vertical.py index 3ac44d7..d6fc70f 100644 --- a/src/velofy/forecasts/models/tactical/vertical.py +++ b/src/velofy/forecasts/models/tactical/vertical.py @@ -88,7 +88,7 @@ class VerticalARIMAModel(base.ForecastingModelABC): data={ 'actual': actuals_ts, 'prediction': ( - seasonal_predictions['prediction'] # noqa:WPS204 + seasonal_predictions['prediction'] + seasonally_adjusted_predictions['prediction'] ), 'low80': ( diff --git a/src/velofy/forecasts/timify.py b/src/velofy/forecasts/timify.py index bfc3a3f..8b858a6 100644 --- a/src/velofy/forecasts/timify.py +++ b/src/velofy/forecasts/timify.py @@ -70,7 +70,7 @@ class OrderHistory: # This happens when there is no demand in the `Pixel` in the given `time_step`. data = pd.read_sql_query( sa.text( - f""" -- # noqa:WPS221 + f""" SELECT pixel_id, start_at, @@ -139,7 +139,7 @@ class OrderHistory: pixel_id, start_at; """, - ), # noqa:WPS355 + ), con=db.connection, index_col=['pixel_id', 'start_at'], ) @@ -240,7 +240,7 @@ class OrderHistory: last_order.minute, ) - def make_horizontal_ts( # noqa:WPS210 + def make_horizontal_ts( self, pixel_id: int, predict_at: dt.datetime, @@ -312,7 +312,7 @@ class OrderHistory: return training_ts, frequency, actuals_ts - def make_vertical_ts( # noqa:WPS210 + def make_vertical_ts( self, pixel_id: int, predict_day: dt.date, @@ -401,7 +401,7 @@ class OrderHistory: return training_ts, frequency, actuals_ts - def make_realtime_ts( # noqa:WPS210 + def make_realtime_ts( self, pixel_id: int, predict_at: dt.datetime, @@ -524,7 +524,7 @@ class OrderHistory: Returns: average number of orders per day """ - training_ts, _, _ = self.make_vertical_ts( # noqa:WPS434 + training_ts, _, _ = self.make_vertical_ts( pixel_id=pixel_id, predict_day=predict_day, train_horizon=train_horizon, diff --git a/src/velofy/init_r.py b/src/velofy/init_r.py index 9afc8c6..5ef24ba 100644 --- a/src/velofy/init_r.py +++ b/src/velofy/init_r.py @@ -19,7 +19,7 @@ rcallbacks.consolewrite_warnerror = lambda msg: None # pragma: no cover # For clarity and convenience, re-raise the error that results from missing R # dependencies with clearer instructions as to how to deal with it. -try: # noqa:WPS229 +try: rpackages.importr('forecast') rpackages.importr('zoo') diff --git a/tests/console/test_gridify.py b/tests/console/test_gridify.py index 762a670..c5600cf 100644 --- a/tests/console/test_gridify.py +++ b/tests/console/test_gridify.py @@ -8,7 +8,7 @@ from velofy.console import gridify @pytest.mark.db -def test_two_pixels_with_two_addresses( # noqa:WPS211 +def test_two_pixels_with_two_addresses( cli, db_session, monkeypatch, diff --git a/tests/db/fake_data/factories/addresses.py b/tests/db/fake_data/factories/addresses.py index 3dde8e2..8615489 100644 --- a/tests/db/fake_data/factories/addresses.py +++ b/tests/db/fake_data/factories/addresses.py @@ -17,7 +17,7 @@ class AddressFactory(alchemy.SQLAlchemyModelFactory): model = db.Address sqlalchemy_get_or_create = ('id',) - id = factory.Sequence(lambda num: num) # noqa:WPS125 + id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) # When testing, all addresses are considered primary ones. diff --git a/tests/db/fake_data/factories/couriers.py b/tests/db/fake_data/factories/couriers.py index d45bde0..c6bf8bd 100644 --- a/tests/db/fake_data/factories/couriers.py +++ b/tests/db/fake_data/factories/couriers.py @@ -14,7 +14,7 @@ class CourierFactory(alchemy.SQLAlchemyModelFactory): model = db.Courier sqlalchemy_get_or_create = ('id',) - id = factory.Sequence(lambda num: num) # noqa:WPS125 + id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) vehicle = 'bicycle' historic_speed = 7.89 diff --git a/tests/db/fake_data/factories/customers.py b/tests/db/fake_data/factories/customers.py index cbef0a5..accd5de 100644 --- a/tests/db/fake_data/factories/customers.py +++ b/tests/db/fake_data/factories/customers.py @@ -13,4 +13,4 @@ class CustomerFactory(alchemy.SQLAlchemyModelFactory): model = db.Customer sqlalchemy_get_or_create = ('id',) - id = factory.Sequence(lambda num: num) # noqa:WPS125 + id = factory.Sequence(lambda num: num) diff --git a/tests/db/fake_data/factories/orders/ad_hoc.py b/tests/db/fake_data/factories/orders/ad_hoc.py index 5052587..f65d0a1 100644 --- a/tests/db/fake_data/factories/orders/ad_hoc.py +++ b/tests/db/fake_data/factories/orders/ad_hoc.py @@ -41,7 +41,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): # Timestamps after `cancelled_at` are discarded # by the `post_generation` hook at the end of the `OrderFactory`. - cancel_ = factory.Trait( # noqa:WPS120 -> leading underscore does not work + cancel_ = factory.Trait( # -> leading underscore does not work cancelled=True, cancelled_at_corrected=False, ) @@ -65,7 +65,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): ) # Generic attributes - id = factory.Sequence(lambda num: num) # noqa:WPS125 + id = factory.Sequence(lambda num: num) # customer -> set by the `make_order` fixture for better control # Attributes regarding the specialization of an `Order`: ad-hoc or scheduled. @@ -182,7 +182,7 @@ class AdHocOrderFactory(alchemy.SQLAlchemyModelFactory): # Statistical attributes -> calculate realistic stats logged_delivery_distance = factory.LazyAttribute( - lambda obj: distance.great_circle( # noqa:WPS317 + lambda obj: distance.great_circle( (obj.pickup_address.latitude, obj.pickup_address.longitude), (obj.delivery_address.latitude, obj.delivery_address.longitude), ).meters, diff --git a/tests/db/fake_data/factories/restaurants.py b/tests/db/fake_data/factories/restaurants.py index 90de785..5d4b81f 100644 --- a/tests/db/fake_data/factories/restaurants.py +++ b/tests/db/fake_data/factories/restaurants.py @@ -18,7 +18,7 @@ class RestaurantFactory(alchemy.SQLAlchemyModelFactory): model = db.Restaurant sqlalchemy_get_or_create = ('id',) - id = factory.Sequence(lambda num: num) # noqa:WPS125 + id = factory.Sequence(lambda num: num) created_at = factory.LazyFunction(utils.early_in_the_morning) name = factory.LazyFunction( lambda: f"{_restaurant_names.first_name()}'s Restaurant", diff --git a/tests/db/fake_data/factories/utils.py b/tests/db/fake_data/factories/utils.py index 367d49f..0e85da2 100644 --- a/tests/db/fake_data/factories/utils.py +++ b/tests/db/fake_data/factories/utils.py @@ -6,7 +6,7 @@ import random from tests import config as test_config -def random_timespan( # noqa:WPS211 +def random_timespan( *, min_hours=0, min_minutes=0, diff --git a/tests/db/test_addresses_addresses.py b/tests/db/test_addresses_addresses.py index 2ae15df..91a209c 100644 --- a/tests/db/test_addresses_addresses.py +++ b/tests/db/test_addresses_addresses.py @@ -21,7 +21,7 @@ def another_address(make_address): @pytest.fixture def path(address, another_address, make_address): """A `Path` from `address` to `another_address`.""" - air_distance = distance.great_circle( # noqa:WPS317 + air_distance = distance.great_circle( address.location.lat_lng, another_address.location.lat_lng, ).meters @@ -31,7 +31,7 @@ def path(address, another_address, make_address): directions = json.dumps( [ (float(add.latitude), float(add.longitude)) - for add in (make_address() for _ in range(5)) # noqa:WPS335 + for add in (make_address() for _ in range(5)) ], ) diff --git a/tests/db/test_forecasts.py b/tests/db/test_forecasts.py index 2e8d2ed..763f05e 100644 --- a/tests/db/test_forecasts.py +++ b/tests/db/test_forecasts.py @@ -376,7 +376,7 @@ class TestConstraints: forecast.low95 = None forecast.high95 = None - forecast.low80, forecast.high80 = ( # noqa:WPS414 + forecast.low80, forecast.high80 = ( forecast.high80, forecast.low80, ) @@ -398,7 +398,7 @@ class TestConstraints: forecast.low80 = None forecast.high80 = None - forecast.low95, forecast.high95 = ( # noqa:WPS414 + forecast.low95, forecast.high95 = ( forecast.high95, forecast.low95, ) @@ -416,7 +416,7 @@ class TestConstraints: assert forecast.low80 is not None assert forecast.low95 is not None - forecast.low80, forecast.low95 = (forecast.low95, forecast.low80) # noqa:WPS414 + forecast.low80, forecast.low95 = (forecast.low95, forecast.low80) db_session.add(forecast) @@ -431,7 +431,7 @@ class TestConstraints: assert forecast.high80 is not None assert forecast.high95 is not None - forecast.high80, forecast.high95 = ( # noqa:WPS414 + forecast.high80, forecast.high95 = ( forecast.high95, forecast.high80, ) diff --git a/tests/db/test_grids.py b/tests/db/test_grids.py index f8d740c..efadf26 100644 --- a/tests/db/test_grids.py +++ b/tests/db/test_grids.py @@ -84,7 +84,7 @@ class TestGridification: """ mock = mocker.Mock() query = ( # noqa:ECE001 - mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501,WPS219 + mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501 ) monkeypatch.setattr(db, 'session', mock) @@ -105,7 +105,7 @@ class TestGridification: result = db.Grid.gridify(city=city, side_length=side_length) assert isinstance(result, db.Grid) - assert len(result.pixels) == 0 # noqa:WPS507 + assert len(result.pixels) == 0 def test_one_pixel_with_one_address(self, city, order, addresses_mock): """At the very least, there must be one `Pixel` ... @@ -155,7 +155,7 @@ class TestGridification: result = db.Grid.gridify(city=city, side_length=side_length) assert isinstance(result, db.Grid) - assert len(result.pixels) == 0 # noqa:WPS507 + assert len(result.pixels) == 0 @pytest.mark.no_cover def test_no_pixel_with_one_address_too_far_west(self, city, order, addresses_mock): @@ -174,7 +174,7 @@ class TestGridification: result = db.Grid.gridify(city=city, side_length=side_length) assert isinstance(result, db.Grid) - assert len(result.pixels) == 0 # noqa:WPS507 + assert len(result.pixels) == 0 @pytest.mark.no_cover def test_two_pixels_with_two_addresses(self, city, make_address, addresses_mock): @@ -206,7 +206,7 @@ class TestGridification: @pytest.mark.db @pytest.mark.no_cover @pytest.mark.parametrize('side_length', [250, 500, 1_000, 2_000, 4_000, 8_000]) - def test_make_random_grids( # noqa:WPS211,WPS218 + def test_make_random_grids( self, db_session, city, diff --git a/tests/db/test_orders.py b/tests/db/test_orders.py index a95799f..04d0761 100644 --- a/tests/db/test_orders.py +++ b/tests/db/test_orders.py @@ -423,7 +423,7 @@ class TestConstraints: 'left_pickup_at', ], ) - def test_unset_timestamp_column_not_marked_as_uncorrected( # noqa:WPS213 + def test_unset_timestamp_column_not_marked_as_uncorrected( self, db_session, order, @@ -507,7 +507,7 @@ class TestConstraints: 'delivery_at', ], ) - def test_set_timestamp_column_is_not_unmarked( # noqa:WPS213 + def test_set_timestamp_column_is_not_unmarked( self, db_session, order, @@ -860,14 +860,14 @@ class TestProperties: assert result > dt.timedelta(0) - def test_scheduled_pickup_at_no_restaurant_notified(self, order): # noqa:WPS118 + def test_scheduled_pickup_at_no_restaurant_notified(self, order): """Test `Order.scheduled_pickup_at` property.""" order.restaurant_notified_at = None with pytest.raises(RuntimeError, match='not set'): int(order.scheduled_pickup_at) - def test_scheduled_pickup_at_no_est_prep_duration(self, order): # noqa:WPS118 + def test_scheduled_pickup_at_no_est_prep_duration(self, order): """Test `Order.scheduled_pickup_at` property.""" order.estimated_prep_duration = None @@ -952,7 +952,7 @@ class TestProperties: assert bool(result) is False - def test_time_to_delivery_no_reached_delivery_at(self, order): # noqa:WPS118 + def test_time_to_delivery_no_reached_delivery_at(self, order): """Test `Order.time_to_delivery` property.""" order.reached_delivery_at = None @@ -972,7 +972,7 @@ class TestProperties: assert result > dt.timedelta(0) - def test_time_at_delivery_no_reached_delivery_at(self, order): # noqa:WPS118 + def test_time_at_delivery_no_reached_delivery_at(self, order): """Test `Order.time_at_delivery` property.""" order.reached_delivery_at = None @@ -1083,7 +1083,7 @@ class TestProperties: @pytest.mark.db @pytest.mark.no_cover -def test_make_random_orders( # noqa:C901,WPS211,WPS213 +def test_make_random_orders( # noqa:C901 db_session, make_address, make_courier, @@ -1096,7 +1096,7 @@ def test_make_random_orders( # noqa:C901,WPS211,WPS213 and `Order` objects adhere to the database constraints. """ # noqa:D202 # Generate a large number of `Order`s to obtain a large variance of data. - for _ in range(1_000): # noqa:WPS122 + for _ in range(1_000): # Ad-hoc `Order`s are far more common than pre-orders. scheduled = random.choice([True, False, False, False, False]) diff --git a/tests/db/test_pixels.py b/tests/db/test_pixels.py index a6a0039..e9c7f5d 100644 --- a/tests/db/test_pixels.py +++ b/tests/db/test_pixels.py @@ -122,7 +122,7 @@ class TestProperties: """A `Mock` whose `.return_value` is `[restaurant]`.""" mock = mocker.Mock() query = ( # noqa:ECE001 - mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501,WPS219 + mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501 ) query.return_value = [restaurant] monkeypatch.setattr(db, 'session', mock) diff --git a/tests/db/utils/test_locations.py b/tests/db/utils/test_locations.py index b777718..204340b 100644 --- a/tests/db/utils/test_locations.py +++ b/tests/db/utils/test_locations.py @@ -98,7 +98,7 @@ class TestSpecialMethods: def test_compare_utm_coordinates_to_themselves(self, location): """Test `Location.__eq__()`.""" - result = location == location # noqa:WPS312 + result = location == location assert result is True diff --git a/tests/forecasts/methods/test_decomposition.py b/tests/forecasts/methods/test_decomposition.py index 00b4b15..3a38c19 100644 --- a/tests/forecasts/methods/test_decomposition.py +++ b/tests/forecasts/methods/test_decomposition.py @@ -221,7 +221,7 @@ class TestValidArguments: @pytest.mark.parametrize('jl', [None, 1]) @pytest.mark.parametrize('ni', [2, 3]) @pytest.mark.parametrize('no', [0, 1]) - def test_decompose_time_series_with_no_demand( # noqa:WPS211,WPS216 + def test_decompose_time_series_with_no_demand( self, vertical_no_demand, nt, @@ -233,7 +233,7 @@ class TestValidArguments: jt, jl, ni, - no, # noqa:WPS110 + no, ): """Decomposing a time series with no demand ... @@ -252,7 +252,7 @@ class TestValidArguments: jt=jt, jl=jl, ni=ni, - no=no, # noqa:WPS110 + no=no, ) result = decomposed.sum().sum() diff --git a/tests/forecasts/test_models.py b/tests/forecasts/test_models.py index 4821ac2..b3b9300 100644 --- a/tests/forecasts/test_models.py +++ b/tests/forecasts/test_models.py @@ -136,7 +136,7 @@ class TestGenericForecastingModelProperties: @pytest.mark.db @pytest.mark.r - def test_make_forecast( # noqa:WPS211 + def test_make_forecast( self, db_session, model_cls, @@ -160,7 +160,7 @@ class TestGenericForecastingModelProperties: @pytest.mark.db @pytest.mark.r - def test_make_forecast_is_cached( # noqa:WPS211 + def test_make_forecast_is_cached( self, db_session, model_cls, diff --git a/tests/forecasts/timify/test_aggregate_orders.py b/tests/forecasts/timify/test_aggregate_orders.py index 3a2534a..da2a8fa 100644 --- a/tests/forecasts/timify/test_aggregate_orders.py +++ b/tests/forecasts/timify/test_aggregate_orders.py @@ -27,7 +27,7 @@ class TestAggregateOrders: """ mock = mocker.Mock() query = ( # noqa:ECE001 - mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501,WPS219 + mock.query.return_value.join.return_value.filter.return_value.all # noqa:E501 ) monkeypatch.setattr(db, 'session', mock) @@ -54,7 +54,7 @@ class TestAggregateOrders: def test_no_orders(self, db_session, one_pixel_grid, restaurant): """Edge case that does not occur for real-life data.""" db_session.commit() - assert len(restaurant.orders) == 0 # noqa:WPS507 sanity check + assert len(restaurant.orders) == 0 # sanity check oh = timify.OrderHistory( grid=one_pixel_grid, @@ -63,7 +63,7 @@ class TestAggregateOrders: result = oh.aggregate_orders() - assert len(result) == 0 # noqa:WPS507 + assert len(result) == 0 def test_evenly_distributed_ad_hoc_orders( self, @@ -99,7 +99,7 @@ class TestAggregateOrders: assert result['n_orders'].max() == 1 assert result['n_orders'].sum() == 12 - def test_evenly_distributed_ad_hoc_orders_with_no_demand_late( # noqa:WPS218 + def test_evenly_distributed_ad_hoc_orders_with_no_demand_late( self, db_session, one_pixel_grid, @@ -212,7 +212,7 @@ class TestAggregateOrders: assert result['n_orders'].max() == 1 assert result['n_orders'].sum() == 1 - def test_evenly_distributed_ad_hoc_orders_with_half_hour_time_steps( # noqa:WPS218 + def test_evenly_distributed_ad_hoc_orders_with_half_hour_time_steps( self, db_session, one_pixel_grid, @@ -273,7 +273,7 @@ class TestAggregateOrders: db_session.add(order) # Create one order every other hour and 6 orders in total. - for hour in range(11, 23, 2): # noqa:WPS440 + for hour in range(11, 23, 2): order = make_order( scheduled=False, restaurant=restaurant, @@ -281,7 +281,7 @@ class TestAggregateOrders: test_config.YEAR, test_config.MONTH, test_config.DAY + 1, - hour, # noqa:WPS441 + hour, 11, ), ) @@ -305,7 +305,7 @@ class TestAggregateOrders: assert result['n_orders'].sum() == 18 @pytest.fixture - def two_pixel_grid( # noqa:WPS211 + def two_pixel_grid( self, db_session, city, @@ -336,7 +336,7 @@ class TestAggregateOrders: return grid - def test_two_pixels_with_shifted_orders( # noqa:WPS218 + def test_two_pixels_with_shifted_orders( self, db_session, two_pixel_grid, @@ -361,7 +361,7 @@ class TestAggregateOrders: db_session.add(order) # Create two orders per hour for `restaurant2`. - for hour in range(11, 23): # noqa:WPS440 + for hour in range(11, 23): order = make_order( scheduled=False, restaurant=restaurant2, @@ -369,7 +369,7 @@ class TestAggregateOrders: test_config.YEAR, test_config.MONTH, test_config.DAY, - hour, # noqa:WPS441 + hour, 13, ), ) @@ -382,7 +382,7 @@ class TestAggregateOrders: test_config.YEAR, test_config.MONTH, test_config.DAY, - hour, # noqa:WPS441 + hour, 14, ), ) diff --git a/tests/forecasts/timify/test_make_time_series.py b/tests/forecasts/timify/test_make_time_series.py index 98f73e0..2250acf 100644 --- a/tests/forecasts/timify/test_make_time_series.py +++ b/tests/forecasts/timify/test_make_time_series.py @@ -119,7 +119,7 @@ class TestMakeHorizontalTimeSeries: train_horizon=train_horizon, ) - _, frequency, _ = result # noqa:WPS434 + _, frequency, _ = result assert frequency == 7 @@ -243,7 +243,7 @@ class TestMakeVerticalTimeSeries: train_horizon=train_horizon, ) - _, frequency, _ = result # noqa:WPS434 + _, frequency, _ = result n_daily_time_steps = ( 60 @@ -423,7 +423,7 @@ class TestMakeRealTimeTimeSeries: train_horizon=train_horizon, ) - _, frequency, _ = result # noqa:WPS434 + _, frequency, _ = result n_daily_time_steps = ( 60 diff --git a/tests/test_config.py b/tests/test_config.py index 84bc883..072e06a 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -38,7 +38,7 @@ def test_database_uri_set(env, monkeypatch): warnings.simplefilter('always') configuration.make_config(env) - assert len(record) == 0 # noqa:WPS441,WPS507 + assert len(record) == 0 @pytest.mark.parametrize('env', envs) @@ -56,7 +56,7 @@ def test_no_database_uri_set_with_testing_env_var(env, monkeypatch): warnings.simplefilter('always') configuration.make_config(env) - assert len(record) == 0 # noqa:WPS441,WPS507 + assert len(record) == 0 @pytest.mark.parametrize('env', envs) @@ -87,7 +87,7 @@ def test_r_libs_path_set(env, monkeypatch): warnings.simplefilter('always') configuration.make_config(env) - assert len(record) == 0 # noqa:WPS441,WPS507 + assert len(record) == 0 @pytest.mark.parametrize('env', envs) @@ -107,7 +107,7 @@ def test_no_r_libs_path_set_with_testing_env_var(env, monkeypatch): warnings.simplefilter('always') configuration.make_config(env) - assert len(record) == 0 # noqa:WPS441,WPS507 + assert len(record) == 0 @pytest.mark.parametrize('env', envs) diff --git a/tests/test_init_r.py b/tests/test_init_r.py index da82254..7a6755a 100644 --- a/tests/test_init_r.py +++ b/tests/test_init_r.py @@ -14,6 +14,6 @@ def test_r_packages_installed(): in the "research/r_dependencies.ipynb" notebook or in the GitHub Actions CI. """ - from velofy import init_r # noqa:WPS433 + from velofy import init_r assert init_r is not None diff --git a/tests/test_version.py b/tests/test_version.py index a4870e5..9e98a45 100644 --- a/tests/test_version.py +++ b/tests/test_version.py @@ -23,7 +23,7 @@ class TestPEP404Compliance: @pytest.fixture def parsed_version(self) -> str: """The packaged version.""" - return pkg_version.Version(velofy.__version__) # noqa:WPS609 + return pkg_version.Version(velofy.__version__) def test_parsed_version_has_no_epoch(self, parsed_version): """PEP440 compliant subset of semantic versioning: no epoch.""" @@ -39,7 +39,7 @@ class TestPEP404Compliance: def test_parsed_version_is_all_public(self, parsed_version): """PEP440 compliant subset of semantic versioning: all public parts.""" - assert parsed_version.public == velofy.__version__ # noqa:WPS609 + assert parsed_version.public == velofy.__version__ class TestSemanticVersioning: @@ -51,7 +51,7 @@ class TestSemanticVersioning: def test_version_is_semantic(self): """Packaged version follows semantic versioning.""" - result = self.version_pattern.fullmatch(velofy.__version__) # noqa:WPS609 + result = self.version_pattern.fullmatch(velofy.__version__) assert result is not None