refactor: more linting and error fixes

This commit is contained in:
Juro Oravec 2025-08-18 11:44:51 +02:00
parent 53a5804706
commit 486fb236bc
10 changed files with 27 additions and 20 deletions

View file

@ -758,20 +758,23 @@ def _map_media_filepaths(media: Type[ComponentMediaInput], map_fn: Callable[[Seq
def _is_media_filepath(filepath: Any) -> bool: def _is_media_filepath(filepath: Any) -> bool:
# Case callable
if callable(filepath): if callable(filepath):
return True return True
if ( # Case SafeString
isinstance(filepath, SafeData) if isinstance(filepath, SafeData) or hasattr(filepath, "__html__"):
or hasattr(filepath, "__html__")
or isinstance(filepath, (Path, os.PathLike))
or hasattr(filepath, "__fspath__")
):
return True return True
# Case PathLike
if isinstance(filepath, (Path, os.PathLike)) or hasattr(filepath, "__fspath__"):
return True
# Case bytes
if isinstance(filepath, bytes): if isinstance(filepath, bytes):
return True return True
# Case str
return isinstance(filepath, str) return isinstance(filepath, str)

View file

@ -1043,7 +1043,7 @@ class ExtensionManager:
if component_ext_subclass: if component_ext_subclass:
bases_list.insert(0, component_ext_subclass) bases_list.insert(0, component_ext_subclass)
bases: tuple[Type, ...] = tuple(bases_list) bases: Tuple[Type, ...] = tuple(bases_list)
# Allow component-level extension class to access the owner `Component` class that via # Allow component-level extension class to access the owner `Component` class that via
# `component_cls`. # `component_cls`.

View file

@ -176,7 +176,7 @@ class CacheExtension(ComponentExtension):
ComponentConfig = ComponentCache ComponentConfig = ComponentCache
def __init__(self, *_args: Any, **_kwargs: Any) -> None: def __init__(self, *_args: Any, **_kwargs: Any) -> None:
self.render_id_to_cache_key: dict[str, str] = {} self.render_id_to_cache_key: Dict[str, str] = {}
def on_component_input(self, ctx: OnComponentInputContext) -> Optional[Any]: def on_component_input(self, ctx: OnComponentInputContext) -> Optional[Any]:
cache_instance = ctx.component.cache cache_instance = ctx.component.cache

View file

@ -36,13 +36,13 @@ def apply_component_highlight(highlight_type: Literal["component", "slot"], outp
output = f""" output = f"""
<style> <style>
.{type}-highlight-{highlight_id}::before {{ .{highlight_type}-highlight-{highlight_id}::before {{
content: "{name}: "; content: "{name}: ";
font-weight: bold; font-weight: bold;
color: {color.text_color}; color: {color.text_color};
}} }}
</style> </style>
<div class="{type}-highlight-{highlight_id}" style="border: 1px solid {color.border_color}"> <div class="{highlight_type}-highlight-{highlight_id}" style="border: 1px solid {color.border_color}">
{output} {output}
</div> </div>
""" """

View file

@ -157,7 +157,8 @@ def set_provided_context_var(
# We turn the kwargs into a NamedTuple so that the object that's "provided" # We turn the kwargs into a NamedTuple so that the object that's "provided"
# is immutable. This ensures that the data returned from `inject` will always # is immutable. This ensures that the data returned from `inject` will always
# have all the keys that were passed to the `provide` tag. # have all the keys that were passed to the `provide` tag.
tuple_cls = NamedTuple("DepInject", provided_kwargs.keys()) # type: ignore[misc] fields = [(field, Any) for field in provided_kwargs]
tuple_cls = NamedTuple("DepInject", fields) # type: ignore[misc]
payload = tuple_cls(**provided_kwargs) payload = tuple_cls(**provided_kwargs)
# Instead of storing the provided data on the Context object, we store it # Instead of storing the provided data on the Context object, we store it

View file

@ -338,7 +338,7 @@ class TestComponentCache:
return {"input": kwargs["input"]} return {"input": kwargs["input"]}
with pytest.raises( with pytest.raises(
ValueError, TypeError,
match=re.escape( match=re.escape(
"Cannot hash slot 'content' of component 'TestComponent' - Slot functions are unhashable.", "Cannot hash slot 'content' of component 'TestComponent' - Slot functions are unhashable.",
), ),

View file

@ -4,7 +4,7 @@ import re
import sys import sys
from pathlib import Path from pathlib import Path
from textwrap import dedent from textwrap import dedent
from typing import Optional from typing import List, Optional
import pytest import pytest
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
@ -344,7 +344,7 @@ class TestComponentMedia:
def test_media_custom_render_js(self): def test_media_custom_render_js(self):
class MyMedia(Media): class MyMedia(Media):
def render_js(self): def render_js(self):
tags: list[str] = [] tags: List[str] = []
for path in self._js: # type: ignore[attr-defined] for path in self._js: # type: ignore[attr-defined]
abs_path = self.absolute_path(path) # type: ignore[attr-defined] abs_path = self.absolute_path(path) # type: ignore[attr-defined]
tags.append(f'<script defer src="{abs_path}"></script>') tags.append(f'<script defer src="{abs_path}"></script>')
@ -370,7 +370,7 @@ class TestComponentMedia:
def test_media_custom_render_css(self): def test_media_custom_render_css(self):
class MyMedia(Media): class MyMedia(Media):
def render_css(self): def render_css(self):
tags: list[str] = [] tags: List[str] = []
media = sorted(self._css) # type: ignore[attr-defined] media = sorted(self._css) # type: ignore[attr-defined]
for medium in media: for medium in media:
for path in self._css[medium]: # type: ignore[attr-defined] for path in self._css[medium]: # type: ignore[attr-defined]
@ -789,7 +789,7 @@ class TestMediaStaticfiles:
class MyMedia(Media): class MyMedia(Media):
def render_js(self): def render_js(self):
tags: list[str] = [] tags: List[str] = []
for path in self._js: # type: ignore[attr-defined] for path in self._js: # type: ignore[attr-defined]
abs_path = self.absolute_path(path) # type: ignore[attr-defined] abs_path = self.absolute_path(path) # type: ignore[attr-defined]
tags.append(f'<script defer src="{abs_path}"></script>') tags.append(f'<script defer src="{abs_path}"></script>')
@ -849,7 +849,7 @@ class TestMediaStaticfiles:
class MyMedia(Media): class MyMedia(Media):
def render_js(self): def render_js(self):
tags: list[str] = [] tags: List[str] = []
for path in self._js: # type: ignore[attr-defined] for path in self._js: # type: ignore[attr-defined]
abs_path = self.absolute_path(path) # type: ignore[attr-defined] abs_path = self.absolute_path(path) # type: ignore[attr-defined]
tags.append(f'<script defer src="{abs_path}"></script>') tags.append(f'<script defer src="{abs_path}"></script>')

View file

@ -201,7 +201,10 @@ class TestComponentAsView:
client = CustomClient(urlpatterns=[path("test/", view)]) client = CustomClient(urlpatterns=[path("test/", view)])
response = client.get("/test/") response = client.get("/test/")
assert response.status_code == 200 assert response.status_code == 200
assert b'<input type="text" name="variable" value="MockComponentRequest">' in response.content assertInHTML(
'<input type="text" name="variable" value="MockComponentRequest">',
response.content.decode(),
)
def test_replace_slot_in_view(self): def test_replace_slot_in_view(self):
class MockComponentSlot(Component): class MockComponentSlot(Component):

View file

@ -121,7 +121,7 @@ class TestSlot:
slot: Slot = Slot(lambda _ctx: "SLOT_FN") slot: Slot = Slot(lambda _ctx: "SLOT_FN")
with pytest.raises( with pytest.raises(
ValueError, TypeError,
match=re.escape("Slot received another Slot instance as `contents`"), match=re.escape("Slot received another Slot instance as `contents`"),
): ):
Slot(slot) Slot(slot)

View file

@ -2434,7 +2434,7 @@ class TestSlotInput:
@djc_test(parametrize=PARAMETRIZE_CONTEXT_BEHAVIOR) @djc_test(parametrize=PARAMETRIZE_CONTEXT_BEHAVIOR)
def test_slots_normalized_as_slot_instances(self, components_settings): def test_slots_normalized_as_slot_instances(self, components_settings):
seen_slots: dict[str, Slot] = {} seen_slots: Dict[str, Slot] = {}
@register("test") @register("test")
class SlottedComponent(Component): class SlottedComponent(Component):