Skip to content

Commit

Permalink
Use 80 chars of code as per PEP8 style
Browse files Browse the repository at this point in the history
  • Loading branch information
vyahello committed Apr 23, 2021
1 parent f8ddec1 commit 1052b81
Show file tree
Hide file tree
Showing 16 changed files with 136 additions and 43 deletions.
12 changes: 9 additions & 3 deletions alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
from sqlalchemy.engine.base import Engine, Connection

# locate 'scooter' package manually
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
)

import scooter.models.__models
from scooter.models import BaseModel
Expand Down Expand Up @@ -45,11 +47,15 @@ def __run_migrations_online() -> None:
and associate a connection with the context.
"""
connectable: Engine = engine_from_config(
config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool,
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)

with connectable.connect() as connection: # type: Connection
context.configure(connection=connection, target_metadata=target_metadata)
context.configure(
connection=connection, target_metadata=target_metadata
)

with context.begin_transaction():
context.run_migrations()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,21 @@
import sqlalchemy as sa


revision: str = '0820c2896135'
revision: str = "0820c2896135"
down_revision: Optional[str] = None
branch_labels: Optional[str] = None
depends_on: Optional[str] = None


def upgrade() -> None:
"""Upgrades migration."""
op.add_column('location', sa.Column('postal', sa.String(), nullable=True))
op.create_index(op.f('ix_location_postal'), 'location', ['postal'], unique=False)
op.add_column("location", sa.Column("postal", sa.String(), nullable=True))
op.create_index(
op.f("ix_location_postal"), "location", ["postal"], unique=False
)


def downgrade() -> None:
"""Downgrades migration."""
op.drop_index(op.f('ix_location_postal'), table_name='location')
op.drop_column('location', 'postal')
op.drop_index(op.f("ix_location_postal"), table_name="location")
op.drop_column("location", "postal")
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@
from alembic import op
import sqlalchemy as sa

revision: str = '4434e19fb4d6'
down_revision: str = '0820c2896135'
revision: str = "4434e19fb4d6"
down_revision: str = "0820c2896135"
branch_labels: Optional[str] = None
depends_on: Optional[str] = None


def upgrade() -> None:
"""Upgrades migration."""
op.add_column('users', sa.Column('gender', sa.String(), nullable=True))
op.add_column("users", sa.Column("gender", sa.String(), nullable=True))


def downgrade() -> None:
"""Downgrades migration."""
op.drop_column('users', 'gender')
op.drop_column("users", "gender")
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tool.black]
line-length = 120
line-length = 80
target-version = ["py36", "py37", "py38"]
exclude = '''
/(
Expand Down
35 changes: 27 additions & 8 deletions scooter/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
from scooter.models.scooters import Scooter
from scooter.models.sessions import create_tables, global_init
from scooter.models.users import User
from scooter.services.service import default_user, parked_scooters, book_scooter, rented_scooters
from scooter.services.service import (
default_user,
parked_scooters,
book_scooter,
rented_scooters,
)

user: User = None

Expand All @@ -20,7 +25,10 @@ def launch_scooter_rental() -> None:
print(f"{f' Electro scooter rental application ':*^100}")
print(f"{f'':*^100}")
print()
options: str = "Please choose a command, [r]ent, [a]vailable, [l]ocate, [h]istory, [q]uit: "
options: str = (
"Please choose a command, "
"[r]ent, [a]vailable, [l]ocate, [h]istory, [q]uit: "
)
command: str = "NOT SET"

while command:
Expand All @@ -31,7 +39,9 @@ def launch_scooter_rental() -> None:
switch.case("l", locate_scooters)
switch.case("h", history)
switch.case(["q", "e"], exit_application)
switch.default(lambda: print(f"Don't know what to do with {command} command."))
switch.default(
lambda: print(f"Don't know what to do with {command} command.")
)


def setup_database() -> None:
Expand All @@ -49,10 +59,13 @@ def available_scooters(suppress_header: bool = False) -> List[Scooter]:
print(f"{f' Available scooters ':*^100}")

list_of_parked_scooters: List[Scooter] = parked_scooters()
for index, scooter in enumerate(list_of_parked_scooters, start=1): # type: int, Scooter
for index, scooter in enumerate(
list_of_parked_scooters, start=1
): # type: int, Scooter
print(
f"#{index}. Loc: {scooter.location.street} {scooter.location.city}, "
f"{scooter.id} {scooter.model} VIN: {scooter.vin} with battery level {scooter.battery_level}%"
f"{scooter.id} {scooter.model} VIN: "
f"{scooter.vin} with battery level {scooter.battery_level}%"
)
print()
return list_of_parked_scooters
Expand Down Expand Up @@ -81,15 +94,19 @@ def locate_scooters() -> None:

print(f"Out with clients [{len(list_of_rented_scooters)} scooters]:")
for rented in list_of_rented_scooters: # type: Scooter
print(f" {rented.id} {rented.model} VIN: {rented.vin} with battery level {rented.battery_level}%")
print(
f" {rented.id} {rented.model} VIN: "
f"{rented.vin} with battery level {rented.battery_level}%"
)

print()

print(f"Parked [{len(list_of_parked_scooters)} scooters]:")
for parked in list_of_parked_scooters: # type: Scooter
print(
f"Location: {parked.location.street} {parked.location.city}, "
f"{parked.id} {parked.model} VIN: {parked.vin} with battery level {parked.battery_level}%"
f"{parked.id} {parked.model} VIN: "
f"{parked.vin} with battery level {parked.battery_level}%"
)


Expand All @@ -98,7 +115,9 @@ def history() -> None:
print(f"{f' Your rental history ':*^100}")
local: User = default_user()
for rental in local.rentals:
print(f" * {rental.start_time.date().isoformat()} {rental.scooter.model}")
print(
f" * {rental.start_time.date().isoformat()} {rental.scooter.model}"
)


def exit_application():
Expand Down
16 changes: 13 additions & 3 deletions scooter/import_.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,17 +88,27 @@ def __import_rentals() -> None:
scooters: List[Scooter] = list(session.query(Scooter))
locations: List[Scooter] = list(session.query(Location))
user: User = default_user()
user2: User = session.query(User).filter(User.email == "user@gmail.com").one()
user2: User = (
session.query(User).filter(User.email == "user@gmail.com").one()
)

for _ in range(1, 3):
selected: Scooter = choice(scooters)
book_scooter(scooter=selected, user=user, start_data=datetime.now() - timedelta(days=randint(1, 100)))
book_scooter(
scooter=selected,
user=user,
start_data=datetime.now() - timedelta(days=randint(1, 100)),
)
scooters.remove(selected)
part_scooter(selected.id, choice(locations).id)

for _ in range(1, 10):
selected = choice(scooters)
book_scooter(scooter=selected, user=user2, start_data=datetime.now() - timedelta(days=randint(1, 100)))
book_scooter(
scooter=selected,
user=user2,
start_data=datetime.now() - timedelta(days=randint(1, 100)),
)
scooters.remove(selected)


Expand Down
14 changes: 11 additions & 3 deletions scooter/infrastructure/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def __init__(self, value: Any) -> None:
def default(self, func: Callable[[], Any]) -> None:
self.case(Switch.__default, func)

def case(self, key, func: Callable[[], Any], fallthrough: bool = False): # noqa: C901
def case( # noqa: C901
self, key, func: Callable[[], Any], fallthrough: bool = False
):
if fallthrough is not None:
if self._falling_through:
self._func_stack.append(func)
Expand Down Expand Up @@ -62,15 +64,21 @@ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
raise exc_val

if not self._func_stack:
raise ValueError(f"Value does not match any case and there is not default case: value {self.value}")
raise ValueError(
"Value does not match any case and there is "
f"not default case: value {self.value}"
)

for func in self._func_stack:
self.__result = func()

@property
def result(self):
if self.__result == Switch.__no_result:
raise ValueError("No result has been computed (did you access Switch.result inside the with block?)")
raise ValueError(
"No result has been computed (did you access "
"Switch.result inside the with block?)"
)
return self.__result


Expand Down
4 changes: 3 additions & 1 deletion scooter/models/rentals.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class Rental(BaseModel):
start_time: Column = Column(DateTime, default=datetime.now, index=True)
end_time: Column = Column(DateTime, index=True)
user_id: Column = Column(Integer, ForeignKey("users.id"), nullable=False)
scooter_id: Column = Column(String, ForeignKey("scooters.id"), nullable=False)
scooter_id: Column = Column(
String, ForeignKey("scooters.id"), nullable=False
)
user = relation("User", back_populates="rentals")
scooter = relation("Scooter")
4 changes: 3 additions & 1 deletion scooter/models/scooters.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,7 @@ class Scooter(BaseModel):
vin: Column = Column(String, index=True, unique=True)
model: Column = Column(String, index=True)
battery_level: Column = Column(Integer, index=True)
location_id: Column = Column(Integer, ForeignKey("location.id"), nullable=True)
location_id: Column = Column(
Integer, ForeignKey("location.id"), nullable=True
)
location = relation("Location")
4 changes: 3 additions & 1 deletion scooter/models/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ def create_tables() -> None:

# noinspection PyUnresolvedReferences
import scooter.models.__models # noqa: F401, pylint: disable=import-outside-toplevel
from scooter.models import BaseModel # pylint: disable=import-outside-toplevel
from scooter.models import (
BaseModel,
) # pylint: disable=import-outside-toplevel

BaseModel.metadata.create_all(__engine)

Expand Down
4 changes: 3 additions & 1 deletion scooter/models/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ class User(BaseModel):
hashed_password: Column = Column(String, nullable=True, index=True)
created_date: Column = Column(DateTime, default=datetime.now, index=True)
last_login: Column = Column(DateTime, default=datetime.now, index=True)
rentals = relation("Rental", order_by=[Rental.start_time.desc()], back_populates="user")
rentals = relation(
"Rental", order_by=[Rental.start_time.desc()], back_populates="user"
)
14 changes: 12 additions & 2 deletions scooter/services/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,19 @@ def part_scooter(scooter_id: int, location_id: int) -> Scooter:

def rented_scooters() -> List[Scooter]:
"""Returns list of rented scooters."""
return list(create_session().query(Scooter).filter(Scooter.location_id == None).all()) # noqa: E711
return list(
create_session()
.query(Scooter)
.filter(Scooter.location_id == None)
.all()
) # noqa: E711


def parked_scooters() -> List[Scooter]:
"""Returns list of parked scooters."""
return list(create_session().query(Scooter).filter(Scooter.location_id != None).all()) # noqa: E711
return list(
create_session()
.query(Scooter)
.filter(Scooter.location_id != None)
.all()
) # noqa: E711
15 changes: 12 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from typing import IO, Sequence
from setuptools import setup as __compose_package, find_packages as __find_packages
from setuptools import (
setup as __compose_package,
find_packages as __find_packages,
)
from scooter import __author__, __email__, __version__, __package_name__


Expand All @@ -25,7 +28,9 @@ def __requirements() -> Sequence[str]:
long_description=__description(),
long_description_content_type="text/markdown",
url="https://github.com/vyahello/rent-electro-scooter",
packages=__find_packages(exclude=("*.tests", "*.tests.*", "tests.*", "tests")),
packages=__find_packages(
exclude=("*.tests", "*.tests.*", "tests.*", "tests")
),
include_package_data=True,
install_requires=__requirements(),
classifiers=(
Expand All @@ -36,5 +41,9 @@ def __requirements() -> Sequence[str]:
"Operating System :: OS Independent",
),
python_requires=">=3.6",
entry_points={"console_scripts": ("scooter-rental = scooter.__main__:launch_scooter_rental",)},
entry_points={
"console_scripts": (
"scooter-rental = scooter.__main__:launch_scooter_rental",
)
},
)
4 changes: 3 additions & 1 deletion tests/database/test_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@


def test_full_path() -> None:
assert full_path("file") == os.path.join(os.getcwd(), "scooter/database/file")
assert full_path("file") == os.path.join(
os.getcwd(), "scooter/database/file"
)
4 changes: 3 additions & 1 deletion tests/infrastructure/test_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from scooter.infrastructure.numbers import make_int


@pytest.mark.parametrize("enter, result", (("10", 10), ("-10", -10), (None, -1), ("", -1), ({}, -1)))
@pytest.mark.parametrize(
"enter, result", (("10", 10), ("-10", -10), (None, -1), ("", -1), ({}, -1))
)
def test_make_int(enter: Any, result: int) -> None:
assert make_int(enter) == result
27 changes: 22 additions & 5 deletions tests/infrastructure/test_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,43 @@ class Range(NamedTuple):


@pytest.fixture(
scope="session", params=(Range(1, 10, range(1, 11)), Range(1, 20, range(1, 21)), Range(1, 30, range(1, 31))),
scope="session",
params=(
Range(1, 10, range(1, 11)),
Range(1, 20, range(1, 21)),
Range(1, 30, range(1, 31)),
),
)
def custom_range(request: SubRequest) -> Range:
return request.param


def test_strict_range(custom_range: Range) -> None:
assert strict_range(custom_range.start, custom_range.stop) == custom_range.range_
assert (
strict_range(custom_range.start, custom_range.stop)
== custom_range.range_
)


def test_strict_range_length(custom_range: Range) -> None:
assert len(strict_range(custom_range.start, custom_range.stop)) == custom_range.stop
assert (
len(strict_range(custom_range.start, custom_range.stop))
== custom_range.stop
)


def test_strict_range_first(custom_range: Range) -> None:
assert strict_range(custom_range.start, custom_range.stop)[0] == custom_range.start
assert (
strict_range(custom_range.start, custom_range.stop)[0]
== custom_range.start
)


def test_strict_range_last(custom_range: Range) -> None:
assert strict_range(custom_range.start, custom_range.stop)[-1] == custom_range.stop
assert (
strict_range(custom_range.start, custom_range.stop)[-1]
== custom_range.stop
)


def test_wrong_strict_range() -> None:
Expand Down

0 comments on commit 1052b81

Please sign in to comment.