Skip to content

Commit a243d27

Browse files
committed
add tests | fix flake8 complaints
1 parent 880c26d commit a243d27

25 files changed

Lines changed: 290 additions & 255 deletions

.flake8

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
[flake8]
2-
ignore = E501
2+
ignore = E501, F401

fastapi_listing/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
from fastapi_listing.factory import strategy_factory, interceptor_factory
22
from fastapi_listing.strategies import QueryStrategy, PaginationStrategy, SortingOrderStrategy
3-
from fastapi_listing.service import ListingService, FastapiListing
3+
from fastapi_listing.service import ListingService, FastapiListing # noqa: F401
44
from fastapi_listing.interceptors import IterativeFilterInterceptor, IndiSorterInterceptor
55

66

7-
__version__ = "0.2.5"
7+
__version__ = "0.2.6"
88

99
strategy_factory.register_strategy("default_paginator", PaginationStrategy)
1010
strategy_factory.register_strategy("default_sorter", SortingOrderStrategy)

fastapi_listing/abstracts/dao.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ class DaoAbstract(metaclass=ABCMeta):
77

88
@property
99
@abstractmethod
10-
def model(self):
10+
def model(self) -> SqlAlchemyModel:
1111
pass
1212

1313
@property
1414
@abstractmethod
15-
def name(self):
15+
def name(self) -> str:
1616
pass
1717

1818
@abstractmethod

fastapi_listing/abstracts/listing.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
from sqlalchemy.orm import Query
22
from abc import ABC, abstractmethod
3-
from typing import Type
43

5-
from fastapi_listing.abstracts import AbsSortingStrategy, \
6-
AbsPaginatingStrategy
74
from fastapi_listing.ctyping import ListingResponseType
85
from fastapi_listing.interface.listing_meta_info import ListingMetaInfo
96
from fastapi_listing.interface.client_site_params_adapter import ClientSiteParamAdapter
@@ -109,7 +106,5 @@ def _allowed_strategy_types(key: str) -> bool:
109106

110107
def switch(self, strategy_type: str, strategy_name: str):
111108
if not self._allowed_strategy_types(strategy_type):
112-
raise ValueError(f"unknown strategy type!")
109+
raise ValueError("unknown strategy type!")
113110
setattr(self, strategy_type, strategy_name)
114-
115-

fastapi_listing/ctyping.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,3 @@ class ListingResponseType(TypedDict):
3030
FastapiRequest = TypeVar("FastapiRequest", bound=Request)
3131
AnySqlAlchemyColumn = TypeVar("AnySqlAlchemyColumn", bound=Column)
3232
SqlAlchemyModel = TypeVar("SqlAlchemyModel", bound=DeclarativeMeta)
33-
34-

fastapi_listing/dao/dao_registry.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ def __init__(self):
77

88
def register_dao(self, key: str, builder):
99
if key is None or not key or type(key) is not str:
10-
raise ValueError(f"Invalid type key, expected str type got {type(key)} for {builder.__name__}!")
10+
raise ValueError(f"Invalid type key, expected str type got {type(key)} for {builder}!")
1111
if key in self._dao:
1212
raise ValueError(f"Dao name {key} already in use with {self._dao[key].__name__}!")
1313
self._dao[key] = builder
@@ -26,7 +26,7 @@ def create(self, key, *, replica=True, master=False, both=False):
2626
elif replica:
2727
dao_obj = dao_(read_db=SessionProvider.read_session)
2828
else:
29-
raise ValueError
29+
raise ValueError("Invalid creation type for dao object allowed types 'replica', 'master', or 'both'")
3030

3131
return dao_obj
3232

fastapi_listing/dao/generic_dao.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from fastapi_listing.ctyping import SqlAlchemyModel
66

77

8-
class GenericDao(DaoAbstract): # type:ignore # noqa
8+
class GenericDao(DaoAbstract):
99
"""
1010
Dao stands for data access object.
1111
This layers encapsulates all logic that a user may write
@@ -39,7 +39,7 @@ def __init__(self, read_db=None, write_db=None):
3939
# we must have two sessions one for read replica and one for master or write replica
4040
# we should define our reusable attributes here that we will use in each dao method definition
4141
# even if we are using single db still having two references for the same session won't hurt
42-
# for future expansion once we decide to move on to read/write replica architecure
42+
# for future expansion once we decide to move on to read/write replica architecture
4343
# we already have groundwork done and only need to push different connections
4444
# from request lifecycle layer.
4545
self._read_db: Session = read_db # kwargs.get("read_db")

fastapi_listing/errors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def __init__(self):
3232
msg = """
3333
No session found! Either you are not currently in a request context,
3434
or you need to manually create a session context and pass the callable to middleware args
35-
e.g.
35+
e.g.
3636
callable -> get_db
3737
app.add_middleware(DaoSessionBinderMiddleware, master=get_db, replica=get_db)
3838
"""

fastapi_listing/factory/_generic_factory.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ def register(key: str, creator: Callable[..., Any]) -> None:
1515

1616
def is_mapper_semantic_valid(mapper_val):
1717
if type(mapper_val) is not tuple:
18-
raise ValueError(f"Invalid filter mapper semantic! Expected tuple!")
19-
if len(mapper_val) < 2 or len(mapper_val) > 2:
20-
raise ValueError(f"Invalid filter mapper semantic {mapper_val}! min tuple length should be 2.")
18+
raise ValueError("Invalid sorter mapper semantic! Expected tuple!")
19+
if len(mapper_val) != 2:
20+
raise ValueError(f"Invalid sorter mapper semantic {mapper_val}! min tuple length should be 2.")
2121
if type(mapper_val[0]) is not str:
22-
ValueError(f"Invalid filter mapper semantic {mapper_val}! first tuple element should be field (str)")
23-
if len(mapper_val) == 3 and not isinstance(mapper_val[1], types.FunctionType):
24-
raise ValueError(f"positional arg error, expects a callable but received: {mapper_val[2]}!")
22+
raise ValueError(f"Invalid sorter mapper semantic {mapper_val}! first tuple element should be field (str)")
23+
if not isinstance(mapper_val[1], types.FunctionType):
24+
raise ValueError(f"positional arg error, expects a callable but received: {mapper_val[1]}!")
2525
return True
2626

2727

fastapi_listing/factory/filter.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,30 @@ def __init__(self):
1313
def register_filter(self, key: str, builder: CommonFilterImpl,
1414
field_extractor_fn: Callable[[str], AnySqlAlchemyColumn] = None):
1515
if key is None or not key:
16-
raise ValueError(f"Invalid type key!")
16+
raise ValueError("Invalid type key!")
1717
if key in self._filters:
1818
raise ValueError(f"filter name already in use with {self._filters[key][0].__name__}!")
1919
self._filters[key] = (builder, field_extractor_fn)
2020

2121
def is_mapper_semantic_valid(self, mapper_val):
2222
if type(mapper_val) is not tuple:
23-
raise ValueError(f"Invalid filter mapper semantic! Expected tuple!")
23+
raise ValueError("Invalid filter mapper semantic! Expected tuple!")
2424
if len(mapper_val) < 2 or len(mapper_val) > 3:
2525
raise ValueError(f"Invalid filter mapper semantic {mapper_val}! min tuple length should be 2.")
2626
if type(mapper_val[0]) is not str:
27-
ValueError(f"Invalid filter mapper semantic {mapper_val}! first tuple element should be field (str)")
27+
raise ValueError(f"Invalid filter mapper semantic {mapper_val}! first tuple element should be field (str)")
2828
if not inspect.isclass(mapper_val[1]):
29-
raise ValueError(f"Invalid filter mapper semantic {mapper_val[1]}! Expects a class!")
30-
if not issubclass(mapper_val[1], CommonFilterImpl):
31-
raise ValueError(f"Invalid filter mapper semantic {mapper_val[1]}!"
29+
raise ValueError(f"Invalid filter mapper semantic {mapper_val[1]!r}! Expects a class!")
30+
if not issubclass(mapper_val[1], CommonFilterImpl) and mapper_val[1] != CommonFilterImpl:
31+
raise ValueError(f"Invalid filter mapper semantic {mapper_val[1]!r}!"
3232
f" Expects a subclass of CommonFilterImpl")
3333
if len(mapper_val) == 3 and not isinstance(mapper_val[2], types.FunctionType):
34-
raise ValueError(f"positional arg error, expects a callable but received: {mapper_val[2]}!")
34+
raise ValueError(f"positional arg error, expects a callable but received: {mapper_val[2]!r}!")
3535
return True
3636

37-
def register_filter_mapper(self, filter_mapper: Dict[str, Tuple[str, CommonFilterImpl,
38-
Optional[Callable[[str], AnySqlAlchemyColumn]]]]):
37+
def register_filter_mapper(
38+
self, filter_mapper: Dict[str, Tuple[str, CommonFilterImpl, Optional[Callable[[str], AnySqlAlchemyColumn]]]]
39+
):
3940
for key, val in filter_mapper.items():
4041
if self.is_mapper_semantic_valid(val):
4142
self.register_filter(val[0], *val[1:])
@@ -44,7 +45,7 @@ def create(self, key: str, **kwargs):
4445
try:
4546
filter_, field_extractor_fn = self._filters[key]
4647
except KeyError:
47-
raise ValueError(f"filter factory couldn't find registered key: {key}")
48+
raise ValueError(f"filter factory couldn't find registered key {key!r}")
4849
return filter_(**kwargs, field_extract_fn=field_extractor_fn)
4950

5051

0 commit comments

Comments
 (0)