Skip to content

Commit

Permalink
linting
Browse files Browse the repository at this point in the history
  • Loading branch information
withtwoemms committed Dec 30, 2023
1 parent 41837fe commit a855973
Show file tree
Hide file tree
Showing 8 changed files with 24 additions and 45 deletions.
1 change: 0 additions & 1 deletion pokedex/api/__main__.py
@@ -1,4 +1,3 @@
import json
import sys
from argparse import ArgumentParser

Expand Down
6 changes: 2 additions & 4 deletions pokedex/api/client.py
@@ -1,12 +1,11 @@
from typing import Generator, Iterable, List, Optional
from actionpack import Procedure

import requests

from actionpack import Procedure
from actionpack.actions import Call
from actionpack.utils import Closure

from pokedex.api import Pokemon, PokeApiEndpoints
from pokedex.api import PokeApiEndpoints, Pokemon
from pokedex.api.constants import BASE_URL
from pokedex.api.models import PokeApiRequest, PokeApiResource, PokeApiResourceRef, PokemonRef

Expand All @@ -16,7 +15,6 @@ def get_endpoints(endpoints_request: PokeApiRequest) -> PokeApiEndpoints:
response.raise_for_status()
endpoints: PokeApiEndpoints = response.json()
if isinstance(endpoints, str):
print(type(endpoints), endpoints)
raise TypeError()
return endpoints

Expand Down
5 changes: 2 additions & 3 deletions pokedex/constants.py
@@ -1,6 +1,5 @@
from pathlib import Path


PROJECTROOT = Path(__file__).parent.parent.absolute()
DBROOT = PROJECTROOT / 'pokedex' / 'db'
CACHEPATH = DBROOT / 'cache'
DBROOT = PROJECTROOT / "pokedex" / "db"
CACHEPATH = DBROOT / "cache"
21 changes: 4 additions & 17 deletions pokedex/db/actions.py
Expand Up @@ -5,23 +5,10 @@

from actionpack import Action

from pokedex.api import Pokemon
from pokedex.constants import CACHEPATH
from pokedex.db.models import DeferredRequest


@dataclass
class DbInsertPokemon(Action):
pokemon: Pokemon
db: Optional[str] = None

def instruction(self) -> bool:
db = self.db or str(CACHEPATH)
with dbm.open(db, 'c') as cache: # create db if not exists
cache[self.name] = json.dumps(self.pokemon, indent=4) # consider alternative serialization
return self.pokemon['name']


@dataclass
class DbInsertRequestResult(Action):
key: AnyStr
Expand All @@ -33,8 +20,8 @@ def __post_init__(self):

def instruction(self) -> bool:
db = self.db or str(CACHEPATH)
response = self.value()
with dbm.open(db, 'c') as cache:
response = self.value() # external call
with dbm.open(db, "c") as cache:
cache[self.key] = json.dumps(response.json())
return True

Expand All @@ -47,7 +34,7 @@ class DbInsert(Action):

def instruction(self) -> str:
db = self.db or str(CACHEPATH)
with dbm.open(db, 'c') as cache:
with dbm.open(db, "c") as cache:
cache[self.key] = self.value
return self.key

Expand All @@ -59,5 +46,5 @@ class DbRead(Action[str, bytes]):

def instruction(self) -> bytes:
db = self.db or str(CACHEPATH)
with dbm.open(db, 'c') as cache: # create db if not exists
with dbm.open(db, "c") as cache: # create db if not exists
return cache[self.key]
8 changes: 3 additions & 5 deletions pokedex/db/client.py
@@ -1,12 +1,11 @@
import json
import requests
from typing import Iterable

import requests
from actionpack import KeyedProcedure

from pokedex.api import Pokemon
from pokedex.db.actions import DbInsert, DbInsertRequestResult, DbRead
from pokedex.db.models import DeferredRequest
from pokedex.db.actions import DbRead, DbInsert, DbInsertRequestResult, DbInsertPokemon


def persist_requests(requests: Iterable[DeferredRequest]):
Expand All @@ -25,6 +24,5 @@ def cached_get(url: str) -> requests.Response:
else:
response = requests.get(url)
response.raise_for_status() # TODO: handle error states
DbInsert(key=url, value=json.dumps(response.json()),
).perform(should_raise=True)
DbInsert(key=url, value=json.dumps(response.json())).perform(should_raise=True)
return response
4 changes: 3 additions & 1 deletion pokedex/db/models.py
@@ -1,7 +1,8 @@
import json
from dataclasses import asdict, dataclass
from requests import Response
from typing import Any, Dict, List, Type, Union

from requests import Response
from typing_extensions import Protocol


Expand All @@ -14,6 +15,7 @@ def __call__(self) -> Response:

JSON = Union[Dict[str, Any], List[Any], int, str, float, bool, Type[None]]


@dataclass
class Report:
persisted: dict
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/__init__.py
@@ -1,6 +1,6 @@
from pathlib import Path
from typing import Dict, TypeVar
from unittest.mock import MagicMock, create_autospec
from unittest.mock import MagicMock

from actionpack.action import Result
from requests.models import Response
Expand Down
22 changes: 9 additions & 13 deletions tests/pokedex/db/test_client.py
Expand Up @@ -7,11 +7,11 @@
from pokedex.api.models import PokeApiRequest
from pokedex.db.actions import DbRead
from pokedex.db.client import cached_get, persist_requests
from tests.fixtures import craft_response, resource, craft_result
from tests.fixtures import craft_response, craft_result, resource


class TestClientCanCache(TestCase):
@patch('pokedex.db.actions.DbInsertRequestResult')
@patch("pokedex.db.actions.DbInsertRequestResult")
@patch.object(
target=PokeApiRequest,
attribute="__call__",
Expand All @@ -20,7 +20,7 @@ class TestClientCanCache(TestCase):
],
)
def test_can_persist_request_(self, mock_request, mock_db_insert):
request_url = 'https://pokeapi.co/api/v2/pokemon/39/'
request_url = "https://pokeapi.co/api/v2/pokemon/39/"
mock_request.url = request_url
key, response_data = next(persist_requests((mock_request,)))
assert key is request_url
Expand All @@ -36,33 +36,29 @@ class TestClientCanRetrieveFromCache(TestCase):
],
)
def test_cache_hit(self, mock_db_reads):
pokemon_response = cached_get('https://pokeapi.co/api/v2/pokemon/39/')
pokemon_response = cached_get("https://pokeapi.co/api/v2/pokemon/39/")
assert pokemon_response.json()["name"] == "jigglypuff"

@patch.object(
target=DbRead,
attribute="perform",
side_effect=[
craft_result(value=Exception('missing key.'), successful=False)
],
side_effect=[craft_result(value=Exception("missing key."), successful=False)],
)
@patch.object(
target=requests,
attribute="get",
side_effect=[
craft_response('something went wrong :/', status_code=500),
craft_response("something went wrong :/", status_code=500),
],
)
def test_cache_miss_request_fail(self, mock_requests, mock_db_reads):
with self.assertRaises(HTTPError):
cached_get('https://pokeapi.co/api/v2/pokemon/39/')
cached_get("https://pokeapi.co/api/v2/pokemon/39/")

@patch.object(
target=DbRead,
attribute="perform",
side_effect=[
craft_result(value=Exception('missing key.'), successful=False)
],
side_effect=[craft_result(value=Exception("missing key."), successful=False)],
)
@patch.object(
target=PokeApiRequest,
Expand All @@ -72,5 +68,5 @@ def test_cache_miss_request_fail(self, mock_requests, mock_db_reads):
],
)
def test_cache_miss_request_success(self, mock_requests, mock_db_reads):
pokemon_response = cached_get('https://pokeapi.co/api/v2/pokemon/39/')
pokemon_response = cached_get("https://pokeapi.co/api/v2/pokemon/39/")
assert pokemon_response.json()["name"] == "jigglypuff"

0 comments on commit a855973

Please sign in to comment.