Skip to content

Commit

Permalink
Fix some typing issues
Browse files Browse the repository at this point in the history
  • Loading branch information
bboonstra committed Oct 22, 2024
1 parent 94383ba commit e578ed1
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 19 deletions.
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
"python.testing.unittestEnabled": true,
"python.testing.unittestArgs": ["-v", "-s", "./tests", "-p", "test_*.py"],
"python.testing.autoTestDiscoverOnSaveEnabled": true,
"liveServer.settings.root": "/docs"
"liveServer.settings.root": "/docs",
"python.analysis.typeCheckingMode": "basic"
}
2 changes: 2 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
## Reporting a Vulnerability

### Light Vulnerabilities

If you find a vulnerability that does not put databases, data, or security at risk, create an issue.

### Severe Vulnerabilities

If you find a severe vulnerability that puts databases, data, or security at risk, [report it confidentially](https://github.com/bboonstra/Effortless/security/advisories/new) or directly message a [maintainer](https://github.com/bboonstra) ASAP.
2 changes: 1 addition & 1 deletion effortless/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def to_dict(self) -> Dict[str, Any]:
}

@staticmethod
def default_headers():
def default_headers() -> Dict[str, Any]:
"""
Create a dictionary with default headers.
Expand Down
31 changes: 16 additions & 15 deletions effortless/effortless.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json
import os
import logging
from typing import Any, Dict, List
from typing import Any, Dict, List, Union
import zlib
import base64
import threading
Expand Down Expand Up @@ -302,12 +302,12 @@ def _read_db(self) -> Dict[str, Any]:
headers = data["headers"]
content = data["content"]

if headers.get("enc"):
content = self._decrypt_data(content)

if headers.get("cmp"):
content = self._decompress_data(content)

if headers.get("enc"):
content = self._decrypt_data(content if isinstance(content, str) else json.dumps(content))

return {"headers": headers, "content": content}
except (IOError, json.JSONDecodeError) as e:
logger.error(f"Error reading database: {str(e)}")
Expand Down Expand Up @@ -338,12 +338,12 @@ def _write_db(self, data: Dict[str, Any], write_in_readonly: bool = False) -> No

headers = data["headers"]
content = data["content"]

if headers.get("cmp"):
content = self._compress_data(content)


if headers.get("enc"):
content = self._encrypt_data(content)

if headers.get("cmp"):
content = self._compress_data(json.dumps(content))

final_data = json.dumps(
{"headers": headers, "content": content}, indent=2
Expand Down Expand Up @@ -381,7 +381,7 @@ def _handle_backup(self) -> None:
self._backup_thread = threading.Thread(target=self._backup)
self._backup_thread.start()

def finish_backup(self, timeout: float = None) -> bool:
def finish_backup(self, timeout: float | None = None) -> bool:
"""
Wait for any ongoing backup operation to complete.
Expand Down Expand Up @@ -429,21 +429,22 @@ def _backup(self) -> bool:
except IOError as e:
logger.error(f"Backup failed: {str(e)}")
return False # Indicate failure

return False

def _compress_data(self, data: Dict[str, Any]) -> str:
def _compress_data(self, data: Union[str, Dict[str, Any]]) -> str:
"""
Compress the given data and return as a base64-encoded string.
This method compresses the input data using zlib compression and then
encodes it as a base64 string for storage.
Args:
data (Dict[str, Any]): The data to be compressed.
data (Union[str, Dict[str, Any]]): The data to be compressed.
Returns:
str: A base64-encoded string of the compressed data.
"""
compressed = zlib.compress(json.dumps(data).encode())
if isinstance(data, dict):
data = json.dumps(data)
compressed = zlib.compress(data.encode())
return base64.b64encode(compressed).decode()

def _decompress_data(self, data: str) -> Dict[str, Any]:
Expand Down
5 changes: 4 additions & 1 deletion effortless/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def _create_field_validator(self):
elif isinstance(self.field, str):
return lambda entry: self._field_exists(entry, self.field)
elif isinstance(self.field, (tuple, list)):
return lambda entry: all(self._field_exists(entry, f) for f in self.field)
return lambda entry: all(self._field_exists(entry, f) for f in self.field) # type: ignore
return lambda entry: False

def __and__(self, other):
Expand Down Expand Up @@ -311,6 +311,8 @@ def condition(entry):
field_value = datetime.fromisoformat(field_value)
except ValueError:
return False
if not isinstance(field_value, datetime):
return False
return start_date <= field_value <= end_date

self.condition = condition
Expand Down Expand Up @@ -528,3 +530,4 @@ class FieldNotFoundError(Exception):
"""

pass

2 changes: 1 addition & 1 deletion tests/test_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ def test_fuzzy_match_type_error(self):

# Test with non-numeric threshold
with self.assertRaises(ValueError):
self.db.filter(Field("name").fuzzy_match("Alice", threshold="high"))
self.db.filter(Field("name").fuzzy_match("Alice", threshold="high")) # type: ignore

def test_fuzzy_match_value_error(self):
# Test with threshold out of range
Expand Down

0 comments on commit e578ed1

Please sign in to comment.