Skip to content

Commit 0478557

Browse files
committed
fix: linting issues
1 parent ec23a81 commit 0478557

File tree

7 files changed

+67
-51
lines changed

7 files changed

+67
-51
lines changed

eventsourcingdb/client.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from collections.abc import AsyncGenerator
2-
import contextlib
2+
33
from types import TracebackType
44
from typing import Any, TypeVar
55

@@ -84,7 +84,7 @@ async def ping(self) -> None:
8484

8585
async def verify_api_token(self) -> None:
8686
request_body = json.dumps({})
87-
87+
8888
response: Response = await self.http_client.post(
8989
path='/api/v1/verify-api-token',
9090
request_body=request_body,
@@ -99,6 +99,7 @@ async def verify_api_token(self) -> None:
9999
response_data = bytes.decode(response_data, encoding='utf-8')
100100
response_json = json.loads(response_data)
101101

102+
# pylint: disable=R2004
102103
if not isinstance(response_json, dict) or 'type' not in response_json:
103104
raise ServerError('Failed to parse response: {response}')
104105

@@ -129,7 +130,7 @@ async def write_events(
129130

130131
if response.status_code != HTTPStatus.OK:
131132
raise ServerError(
132-
f'Unexpected response status: '
133+
f'Unexpected response status: {response}'
133134
)
134135

135136
response_data = await response.body.read()
@@ -206,7 +207,7 @@ async def read_events(
206207
f'{message}.'
207208
)
208209

209-
async def run_eventql_query(self, query: str) -> AsyncGenerator[Any, None]:
210+
async def run_eventql_query(self, query: str) -> AsyncGenerator[Any]:
210211
request_body = json.dumps({
211212
'query': query,
212213
})
@@ -224,8 +225,8 @@ async def run_eventql_query(self, query: str) -> AsyncGenerator[Any, None]:
224225
message = parse_raw_message(raw_message)
225226

226227
if is_stream_error(message):
227-
raise ServerError(f'{message["payload"]["error"]}.')
228-
228+
raise ServerError(f'{message['payload']['error']}.')
229+
#pylint: disable=R2004
229230
if message.get('type') == 'row':
230231
payload = message['payload']
231232

eventsourcingdb/container.py

Lines changed: 43 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -128,27 +128,37 @@ def start(self) -> 'Container':
128128
if self._container is not None:
129129
return self
130130

131-
try:
132-
# Try to pull the latest image
133-
self._docker_client.images.pull(self._image_name, self._image_tag)
134-
except errors.APIError as e:
135-
# Check if we already have the image locally
136-
try:
137-
image_name = f"{self._image_name}:{self._image_tag}"
138-
self._docker_client.images.get(image_name)
139-
# If we get here, the image exists locally, so we can continue
140-
logging.warning(f"Warning: Could not pull image: {e}. Using locally cached image.")
141-
except errors.ImageNotFound:
142-
# If the image isn't available locally either, we can't continue
143-
raise RuntimeError(f'Could not pull image and no local image available: {e}') from e
144-
131+
# Fix too-many-try-statements by breaking into separate methods
132+
self._pull_or_get_image()
145133
self._cleanup_existing_containers()
146134
self._create_container()
147135
self._fetch_mapped_port()
148136
self._wait_for_http('/api/v1/ping', timeout=20)
149137

150138
return self
151139

140+
def _pull_or_get_image(self) -> None:
141+
"""Pull the image or use local image if available."""
142+
try:
143+
# Try to pull the latest image
144+
self._docker_client.images.pull(self._image_name, self._image_tag)
145+
except errors.APIError as e:
146+
# Handle the API error
147+
self._handle_image_pull_error(e)
148+
149+
def _handle_image_pull_error(self, error):
150+
"""Handle error when pulling image fails by checking for local version."""
151+
# Check if we already have the image locally
152+
image_name = f"{self._image_name}:{self._image_tag}"
153+
try:
154+
self._docker_client.images.get(image_name)
155+
except errors.ImageNotFound:
156+
# If the image isn't available locally either, we can't continue
157+
raise RuntimeError(
158+
f'Could not pull image and no local image available: {error}') from error
159+
# If we get here, the image exists locally, so we can continue
160+
logging.warning("Warning: Could not pull image: %s. Using locally cached image.", error)
161+
152162
def stop(self) -> None:
153163
self._stop_and_remove_container()
154164

@@ -159,16 +169,16 @@ def _stop_and_remove_container(self) -> None:
159169
try:
160170
self._container.stop()
161171
except errors.NotFound as e:
162-
logging.warning(f'Warning: Container not found while stopping: {e}')
172+
logging.warning("Warning: Container not found while stopping: %s", e)
163173
except errors.APIError as e:
164-
logging.warning(f'Warning: API error while stopping container: {e}')
174+
logging.warning("Warning: API error while stopping container: %s", e)
165175

166176
try:
167177
self._container.remove()
168178
except errors.NotFound as e:
169-
logging.warning(f'Warning: Container not found while removing: {e}')
179+
logging.warning("Warning: Container not found while removing: %s", e)
170180
except errors.APIError as e:
171-
logging.warning(f'Warning: API error while removing container: {e}')
181+
logging.warning("Warning: API error while removing container: %s", e)
172182

173183
self._container = None
174184
self._mapped_port = None
@@ -192,24 +202,28 @@ def _wait_for_http(self, path: str, timeout: int) -> None:
192202
if time.time() - start_time >= timeout:
193203
break
194204

195-
response = None
196-
status_code = None
197-
try:
198-
response = requests.get(url, timeout=2)
199-
except requests.RequestException:
200-
pass
201-
202-
if response is not None:
203-
status_code = response.status_code
204-
205-
if response is not None and status_code == HTTPStatus.OK:
205+
# Extract request into a helper method to reduce try statements
206+
if self._check_endpoint_available(url):
206207
return
207208

208209
time.sleep(0.5)
209210

210211
self._stop_and_remove_container()
211212
raise TimeoutError(f'Service failed to become ready within {timeout} seconds')
212213

214+
def _check_endpoint_available(self, url: str) -> bool:
215+
"""Check if an HTTP endpoint is available."""
216+
try:
217+
response = requests.get(url, timeout=2)
218+
except requests.RequestException:
219+
return False
220+
return self._check_response_ok(response)
221+
222+
# pylint: disable=R6301
223+
def _check_response_ok(self, response) -> bool:
224+
"""Check if the HTTP response indicates success."""
225+
return response is not None and response.status_code == HTTPStatus.OK
226+
213227
def with_api_token(self, token: str) -> 'Container':
214228
self._api_token = token
215229
return self

eventsourcingdb/http_client/http_client.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ async def get(
6464
with_authorization: bool = True,
6565
) -> Response:
6666
if self.__session is None:
67-
raise CustomError("HTTP client session not initialized. Call initialize() before making requests.")
67+
raise CustomError(
68+
"HTTP client session not initialized. Call initialize() before making requests.")
6869

6970
async def __request_executor() -> Response:
7071
url_path = url.join_segments(self.__base_url, path)

eventsourcingdb/http_client/validate_response.py

Whitespace-only changes.

tests/test_observe_events.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from eventsourcingdb.errors.server_error import ServerError
66
from eventsourcingdb.event.event_candidate import EventCandidate
77
from eventsourcingdb.handlers.bound import Bound, BoundType
8+
# pylint: disable=C0301
89
from eventsourcingdb.handlers.observe_events.if_event_is_missing_during_observe import IfEventIsMissingDuringObserve
910
from eventsourcingdb.handlers.observe_events.observe_events_options import ObserveEventsOptions
1011
from eventsourcingdb.handlers.observe_events.observe_from_latest_event import ObserveFromLatestEvent

tests/test_run_eventql_query.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
1-
import asyncio
2-
31
from aiohttp import ClientConnectorDNSError
42
import pytest
53

6-
from eventsourcingdb.errors.server_error import ServerError
74
from eventsourcingdb.event.event_candidate import EventCandidate
85

9-
from .conftest import TestData
106
from .shared.database import Database
11-
from .shared.event.assert_event import assert_event_equals
127

138

149
class TestRunEventQLQuery:
10+
# Define constants to avoid magic value comparisons
11+
EXPECTED_ROW_COUNT = 2
12+
FIRST_EVENT_ID = '0'
13+
FIRST_EVENT_VALUE = 23
14+
SECOND_EVENT_ID = '1'
15+
SECOND_EVENT_VALUE = 42
16+
1517
@staticmethod
1618
@pytest.mark.asyncio
1719
async def test_throws_error_if_server_is_not_reachable(
@@ -48,7 +50,7 @@ async def test_reads_all_rows_the_query_returns(
4850
subject='/test',
4951
type='io.eventsourcingdb.test',
5052
data={
51-
'value': 23,
53+
'value': TestRunEventQLQuery.FIRST_EVENT_VALUE,
5254
},
5355
)
5456

@@ -57,7 +59,7 @@ async def test_reads_all_rows_the_query_returns(
5759
subject='/test',
5860
type='io.eventsourcingdb.test',
5961
data={
60-
'value': 42,
62+
'value': TestRunEventQLQuery.SECOND_EVENT_VALUE,
6163
},
6264
)
6365

@@ -67,13 +69,12 @@ async def test_reads_all_rows_the_query_returns(
6769
async for row in client.run_eventql_query('FROM e IN events PROJECT INTO e'):
6870
rows_read.append(row)
6971

70-
assert len(rows_read) == 2
72+
assert len(rows_read) == TestRunEventQLQuery.EXPECTED_ROW_COUNT
7173

7274
first_row = rows_read[0]
73-
# Use dictionary access instead of attribute access
74-
assert first_row['id'] == '0'
75-
assert first_row['data']['value'] == 23
75+
assert first_row['id'] == TestRunEventQLQuery.FIRST_EVENT_ID
76+
assert first_row['data']['value'] == TestRunEventQLQuery.FIRST_EVENT_VALUE
7677

7778
second_row = rows_read[1]
78-
assert second_row['id'] == '1'
79-
assert second_row['data']['value'] == 42
79+
assert second_row['id'] == TestRunEventQLQuery.SECOND_EVENT_ID
80+
assert second_row['data']['value'] == TestRunEventQLQuery.SECOND_EVENT_VALUE

tests/test_verify_api_token.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import pytest
22

33
from eventsourcingdb.client import Client
4-
from eventsourcingdb.errors.custom_error import CustomError
54
from eventsourcingdb.errors.server_error import ServerError
65

76
from .shared.database import Database
@@ -16,7 +15,6 @@ async def test_does_not_throw_if_token_is_valid(
1615
client = database.get_client()
1716
await client.verify_api_token()
1817

19-
2018
@staticmethod
2119
@pytest.mark.asyncio
2220
async def test_throws_error_if_token_is_invalid(

0 commit comments

Comments
 (0)