internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: litestar-org/litestar

Issue:
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32


Discussion:
I agree. Do you want to submit a PR?

Resolving patch:
diff --git a/litestar/_signature/models/attrs_signature_model.py b/litestar/_signature/models/attrs_signature_model.py
--- a/litestar/_signature/models/attrs_signature_model.py
+++ b/litestar/_signature/models/attrs_signature_model.py
@@ -221,8 +221,13 @@ def __init__(self) -> None:
 
         # ensure attrs instances are not unstructured into dict
         self.register_unstructure_hook_factory(
-            lambda value: attrs.has(value) and AttrsSignatureModel not in list(value.__mro__),
-            _pass_through_unstructure_hook,
+            # the first parameter is a predicate that tests the value. In this case we are testing for an attrs
+            # decorated class that does not have the AttrsSignatureModel anywhere in its mro chain.
+            lambda x: attrs.has(x) and AttrsSignatureModel not in list(x.__mro__),
+            # the "unstructuring" hook we are registering is a lambda that receives the class constructor and returns
+            # another lambda that will take a value and receive it unmodified.
+            # this is a hack to ensure that no attrs constructors are called during unstructuring.
+            lambda x: lambda x: x,
         )
 
         for cls, structure_hook in hooks:


Test patch:
diff --git a/tests/kwargs/test_attrs_data.py b/tests/kwargs/test_attrs_data.py
new file mode 100644
--- /dev/null
+++ b/tests/kwargs/test_attrs_data.py
@@ -0,0 +1,22 @@
+from attrs import define
+
+from litestar import post
+from litestar.status_codes import HTTP_201_CREATED
+from litestar.testing import create_test_client
+
+
+def test_parsing_of_attrs_data() -> None:
+    @define(slots=True, frozen=True)
+    class AttrsUser:
+        name: str
+        email: str
+
+    @post("/")
+    async def attrs_data(data: AttrsUser) -> AttrsUser:
+        return data
+
+    with create_test_client([attrs_data]) as client:
+        response = client.post("/", json={"name": "foo", "email": "e@example.com"})
+        assert response.status_code == HTTP_201_CREATED
+        assert response.json().get("name") == "foo"
+        assert response.json().get("email") == "e@example.com"
Repository: litestar-org/litestar

Issue:
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32


Discussion:
I agree. Do you want to submit a PR?

Resolving patch:
diff --git a/litestar/dto/factory/_backends/msgspec/utils.py b/litestar/dto/factory/_backends/msgspec/utils.py
--- a/litestar/dto/factory/_backends/msgspec/utils.py
+++ b/litestar/dto/factory/_backends/msgspec/utils.py
@@ -24,7 +24,7 @@ def _create_msgspec_field(field_definition: FieldDefinition) -> MsgspecField | N
     if field_definition.default is not Empty:
         kws["default"] = field_definition.default
 
-    if field_definition.default_factory is not None:
+    elif field_definition.default_factory is not None:
         kws["default_factory"] = field_definition.default_factory
 
     if not kws:


Test patch:
Repository: litestar-org/litestar

Issue:
Bug: Missing declarations from `__all__`
### Description

There are some items missing declarations in their respective `__all__` vars that need fixing.

While there are some listed in the `MCVE` below, there may be more.

### URL to code causing the issue

https://github.com/litestar-org/litestar/

### MCVE

```python
from litestar.middleware.exceptions.middleware import ExceptionResponseContent 
from litestar.middleware.exceptions.middleware import create_exception_response
from litestar.serialization import DEFAULT_TYPE_ENCODERS
from litestar.data_extractors import RequestExtractorField
from litestar.data_extractors import ResponseExtractorField
```


### Steps to reproduce

```bash
1. Try to import one of the above items in the MCVE.
2. See your IDE yell at you for missing `__all__` declarations.
3. Contemplate, yet again, going to drive trains for a living.
```


### Screenshots

```bash
N/A
```


### Logs

```bash
N/A
```


### Litestar Version

2.0.0alpha3

### Platform

- [ ] Linux
- [ ] Mac
- [ ] Windows
- [x] Other (Please specify in the description above)
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32


Discussion:

I agree. Do you want to submit a PR?

Resolving patch:
diff --git a/litestar/data_extractors.py b/litestar/data_extractors.py
--- a/litestar/data_extractors.py
+++ b/litestar/data_extractors.py
@@ -7,7 +7,14 @@
 from litestar.datastructures.upload_file import UploadFile
 from litestar.enums import HttpMethod, RequestEncodingType
 
-__all__ = ("ConnectionDataExtractor", "ExtractedRequestData", "ExtractedResponseData", "ResponseDataExtractor")
+__all__ = (
+    "ConnectionDataExtractor",
+    "ExtractedRequestData",
+    "ExtractedResponseData",
+    "ResponseDataExtractor",
+    "RequestExtractorField",
+    "ResponseExtractorField",
+)
 
 
 if TYPE_CHECKING:
diff --git a/litestar/middleware/exceptions/middleware.py b/litestar/middleware/exceptions/middleware.py
--- a/litestar/middleware/exceptions/middleware.py
+++ b/litestar/middleware/exceptions/middleware.py
@@ -15,7 +15,7 @@
 from litestar.middleware.exceptions._debug_response import create_debug_response
 from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
 
-__all__ = ("ExceptionHandlerMiddleware",)
+__all__ = ("ExceptionHandlerMiddleware", "ExceptionResponseContent", "create_exception_response")
 
 
 if TYPE_CHECKING:


Test patch:
Repository: litestar-org/litestar

Issue:
Docs: template autoescaping behavior
### Summary

I appreciate this framework having a built-in choice between Jinja and Mako.  The documentation however makes no mention of a significant difference in the Litestar behavior between the two -- that using the Jinja engine will autoescape for you, whereas Mako will not.  


Discussion:
Or just make the functionality match and autoescape Mako by default, which is the expected behavior.

The instantiation here:
https://github.com/litestar-org/litestar/blob/4c1c9c486d4f50027faadec35728e5c51edf1808/litestar/contrib/mako.py#L73

Adding the following kwarg:
```python
 default_filters=['h']
```

Jinja instantiation:
https://github.com/litestar-org/litestar/blob/4c1c9c486d4f50027faadec35728e5c51edf1808/litestar/contrib/jinja.py#L40

Relevant Mako docs:
https://docs.makotemplates.org/en/latest/filtering.html#filtering-default-filters



Resolving patch:
diff --git a/litestar/contrib/mako.py b/litestar/contrib/mako.py
--- a/litestar/contrib/mako.py
+++ b/litestar/contrib/mako.py
@@ -70,7 +70,9 @@ def __init__(self, directory: DirectoryPath | list[DirectoryPath]) -> None:
             directory: Direct path or list of directory paths from which to serve templates.
         """
         super().__init__(directory=directory)
-        self.engine = TemplateLookup(directories=directory if isinstance(directory, (list, tuple)) else [directory])
+        self.engine = TemplateLookup(
+            directories=directory if isinstance(directory, (list, tuple)) else [directory], default_filters=["h"]
+        )
         self._template_callables: list[tuple[str, Callable[[dict[str, Any]], Any]]] = []
         self.register_template_callable(key="url_for_static_asset", template_callable=url_for_static_asset)  # type: ignore
         self.register_template_callable(key="csrf_token", template_callable=csrf_token)  # type: ignore


Test patch:
diff --git a/tests/template/test_template.py b/tests/template/test_template.py
--- a/tests/template/test_template.py
+++ b/tests/template/test_template.py
@@ -51,6 +51,12 @@ def callback(engine: JinjaTemplateEngine) -> None:
 @pytest.mark.parametrize("engine", (JinjaTemplateEngine, MakoTemplateEngine))
 def test_engine_instance(engine: Type["TemplateEngineProtocol"], template_dir: "Path") -> None:
     engine_instance = engine(template_dir)
+    if isinstance(engine_instance, JinjaTemplateEngine):
+        assert engine_instance.engine.autoescape is True
+
+    if isinstance(engine_instance, MakoTemplateEngine):
+        assert engine_instance.engine.template_args["default_filters"] == ["h"]
+
     config = TemplateConfig(engine=engine_instance)
     assert config.engine_instance is engine_instance
Repository: litestar-org/litestar

Issue:
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32


Discussion:
I agree. Do you want to submit a PR?

Resolving patch:
diff --git a/litestar/contrib/pydantic.py b/litestar/contrib/pydantic.py
--- a/litestar/contrib/pydantic.py
+++ b/litestar/contrib/pydantic.py
@@ -32,9 +32,10 @@ class PydanticDTO(AbstractDTOFactory[T], Generic[T]):
 
     @classmethod
     def generate_field_definitions(cls, model_type: type[BaseModel]) -> Generator[FieldDefinition, None, None]:
-        for key, parsed_type in get_model_type_hints(model_type).items():
+        model_parsed_types = get_model_type_hints(model_type)
+        for key, model_field in model_type.__fields__.items():
+            parsed_type = model_parsed_types[key]
             model_field = model_type.__fields__[key]
-
             dto_field: DTOField | None = model_field.field_info.extra.get(DTO_FIELD_META_KEY)
 
             def determine_default(_parsed_type: ParsedType, _model_field: ModelField) -> Any:


Test patch:
diff --git a/tests/contrib/test_pydantic.py b/tests/contrib/test_pydantic.py
--- a/tests/contrib/test_pydantic.py
+++ b/tests/contrib/test_pydantic.py
@@ -11,6 +11,7 @@
 from litestar.typing import ParsedType
 
 if TYPE_CHECKING:
+    from types import ModuleType
     from typing import Callable
 
 
@@ -42,3 +43,30 @@ class NotModel:
 
     assert PydanticDTO.detect_nested_field(ParsedType(TestModel)) is True
     assert PydanticDTO.detect_nested_field(ParsedType(NotModel)) is False
+
+
+def test_generate_field_definitions_from_beanie_models(create_module: Callable[[str], ModuleType]) -> None:
+    module = create_module(
+        """
+from typing import Optional
+
+import pymongo
+from pydantic import BaseModel
+
+from beanie import Document
+
+
+class Category(BaseModel):
+    name: str
+    description: str
+
+
+class Product(Document):  # This is the model
+    name: str
+    description: Optional[str] = None
+    price: float
+    category: Category
+"""
+    )
+    field_names = [field.name for field in PydanticDTO.generate_field_definitions(module.Product)]
+    assert field_names == ["id", "revision_id", "name", "description", "price", "category"]
Repository: litestar-org/litestar

Issue:
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32


Discussion:
I agree. Do you want to submit a PR?

Resolving patch:
diff --git a/litestar/contrib/repository/filters.py b/litestar/contrib/repository/filters.py
--- a/litestar/contrib/repository/filters.py
+++ b/litestar/contrib/repository/filters.py
@@ -8,7 +8,13 @@
 
 T = TypeVar("T")
 
-__all__ = ["BeforeAfter", "CollectionFilter", "LimitOffset", "OrderBy", "SearchFilter"]
+__all__ = (
+    "BeforeAfter",
+    "CollectionFilter",
+    "LimitOffset",
+    "OrderBy",
+    "SearchFilter",
+)
 
 
 @dataclass
diff --git a/litestar/dto/exceptions.py b/litestar/dto/exceptions.py
--- a/litestar/dto/exceptions.py
+++ b/litestar/dto/exceptions.py
@@ -2,7 +2,7 @@
 
 from litestar.exceptions import ImproperlyConfiguredException
 
-__all__ = ["DTOException", "UnsupportedType"]
+__all__ = ("DTOException", "UnsupportedType")
 
 
 class DTOException(ImproperlyConfiguredException):
diff --git a/litestar/dto/factory/abc.py b/litestar/dto/factory/abc.py
--- a/litestar/dto/factory/abc.py
+++ b/litestar/dto/factory/abc.py
@@ -27,7 +27,7 @@
     from ._backends import AbstractDTOBackend
     from .types import FieldDefinition
 
-__all__ = ["AbstractDTOFactory"]
+__all__ = ("AbstractDTOFactory",)
 
 T = TypeVar("T")
 


Test patch:
Repository: litestar-org/litestar

Issue:
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32


Discussion:
I agree. Do you want to submit a PR?

Resolving patch:
diff --git a/litestar/dto/exceptions.py b/litestar/dto/exceptions.py
deleted file mode 100644
--- a/litestar/dto/exceptions.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from __future__ import annotations
-
-from litestar.exceptions import ImproperlyConfiguredException
-
-__all__ = ("DTOException", "UnsupportedType")
-
-
-class DTOException(ImproperlyConfiguredException):
-    """Base exception for DTO errors."""
-
-
-class UnsupportedType(DTOException):
-    """Raised when a type is not supported by Litestar."""


Test patch:
Repository: litestar-org/litestar

Issue:
Enhancement: Only run Sonar & Snyk on forks
### Summary

When forking the repo, tests are brought with it but Snyk & Sonar CI fails because the secrets are not set.

### Basic Example

Add ` && github.repository_owner == 'starlite-api'` to the if-check in `ci.yaml` to prevent these two CI items from running on non-upstream repos.

### Drawbacks and Impact

_No response_

### Unresolved questions

_No response_


Discussion:

Resolving patch:
diff --git a/litestar/types/composite_types.py b/litestar/types/composite_types.py
--- a/litestar/types/composite_types.py
+++ b/litestar/types/composite_types.py
@@ -12,6 +12,7 @@
     Iterator,
     Literal,
     Mapping,
+    MutableMapping,
     Sequence,
     Set,
     Tuple,
@@ -45,7 +46,7 @@
 
 
 Dependencies = Mapping[str, Union[Provide, AnyCallable]]
-ExceptionHandlersMap = Mapping[Union[int, Type[Exception]], ExceptionHandler]
+ExceptionHandlersMap = MutableMapping[Union[int, Type[Exception]], ExceptionHandler]
 MaybePartial = Union[T, partial]
 Middleware = Union[
     Callable[..., ASGIApp], DefineMiddleware, Iterator[Tuple[ASGIApp, Dict[str, Any]]], Type[MiddlewareProtocol]


Test patch:
Repository: litestar-org/litestar

Issue:
Docs: DTO Factory exclude fields in nested complex types
### Summary

Need to document procedure for excluding fields from nested complex types, e.g.,

```py
class Model1:
    a: int
    b: str

class Model2:
    c: int
    d: str

class Model3:
    e: Union[Model1, Model2]

config = DTOConfig(exclude={"e.0.a", "e.1.c"})
...
```


Discussion:

Resolving patch:
diff --git a/docs/examples/data_transfer_objects/factory/excluding_fields.py b/docs/examples/data_transfer_objects/factory/excluding_fields.py
--- a/docs/examples/data_transfer_objects/factory/excluding_fields.py
+++ b/docs/examples/data_transfer_objects/factory/excluding_fields.py
@@ -1,4 +1,5 @@
 from datetime import datetime
+from typing import List
 from uuid import UUID
 
 from sqlalchemy import ForeignKey
@@ -19,16 +20,30 @@ class Address(Base):
     zip: Mapped[str]
 
 
+class Pets(Base):
+    name: Mapped[str]
+    user_id: Mapped[UUID] = mapped_column(ForeignKey("user.id"))
+
+
 class User(Base):
     name: Mapped[str]
     password: Mapped[str] = mapped_column(info=dto_field("private"))
     created_at: Mapped[datetime] = mapped_column(info=dto_field("read-only"))
     address_id: Mapped[UUID] = mapped_column(ForeignKey("address.id"), info=dto_field("private"))
     address: Mapped[Address] = relationship(info=dto_field("read-only"))
+    pets: Mapped[List[Pets]] = relationship(info=dto_field("read-only"))
 
 
 UserDTO = SQLAlchemyDTO[User]
-config = DTOConfig(exclude={"id", "address.id", "address.street"})
+config = DTOConfig(
+    exclude={
+        "id",
+        "address.id",
+        "address.street",
+        "pets.0.id",
+        "pets.0.user_id",
+    }
+)
 ReadUserDTO = SQLAlchemyDTO[Annotated[User, config]]
 
 
@@ -36,6 +51,7 @@ class User(Base):
 def create_user(data: User) -> User:
     data.created_at = datetime.min
     data.address = Address(street="123 Main St", city="Anytown", state="NY", zip="12345")
+    data.pets = [Pets(id=1, name="Fido"), Pets(id=2, name="Spot")]
     return data
 
 


Test patch:
diff --git a/docs/examples/tests/data_transfer_objects/factory/test_example_apps.py b/docs/examples/tests/data_transfer_objects/factory/test_example_apps.py
--- a/docs/examples/tests/data_transfer_objects/factory/test_example_apps.py
+++ b/docs/examples/tests/data_transfer_objects/factory/test_example_apps.py
@@ -58,3 +58,20 @@ def test_patch_requests_app() -> None:
             "name": "Peter Pan",
             "age": 40,
         }
+
+
+def test_exclude_fields_app() -> None:
+    from docs.examples.data_transfer_objects.factory.excluding_fields import app
+
+    with TestClient(app) as client:
+        response = client.post(
+            "/users",
+            json={"name": "Litestar User", "password": "xyz", "created_at": "2023-04-24T00:00:00Z"},
+        )
+        assert response.status_code == 201
+        assert response.json() == {
+            "created_at": "0001-01-01T00:00:00",
+            "address": {"city": "Anytown", "state": "NY", "zip": "12345"},
+            "pets": [{"name": "Fido"}, {"name": "Spot"}],
+            "name": "Litestar User",
+        }
Repository: litestar-org/litestar

Issue:
Bug: OpenApi generation for `Dict[str, X]`
### Description

The generated OpenApi schema for `Dict[str, X]` ignores `X`: for example `Dict[str, int]` generates just 
`{"type": "object"}` 
instead of 
`{"type": "object", "additionalProperties": { "type": "integer" }}`. 

In comparison `List[X]` generates the correct schema 
`{"items": {"type": "integer"}, "type": "array"}` \
instead of just 
`{"type": "array"}`



### URL to code causing the issue

_No response_

### MCVE

_No response_

### Steps to reproduce

_No response_

### Screenshots

_No response_

### Logs

_No response_

### Litestar Version

Main branch

### Platform

- [ ] Linux
- [ ] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)


Discussion:
Thanks for the report!

The behavior can be observed in our [hello-world](https://github.com/litestar-org/litestar-hello-world) app too:

![image](https://github.com/litestar-org/litestar/assets/20659309/c15cdf96-5789-448e-b416-9265ff50b7c4)

PRs welcome!

Resolving patch:
diff --git a/litestar/_openapi/schema_generation/schema.py b/litestar/_openapi/schema_generation/schema.py
--- a/litestar/_openapi/schema_generation/schema.py
+++ b/litestar/_openapi/schema_generation/schema.py
@@ -439,7 +439,20 @@ def create_schema_for_object_type(
         A schema instance.
     """
     if field.is_mapping:
-        return Schema(type=OpenAPIType.OBJECT)
+        return Schema(
+            type=OpenAPIType.OBJECT,
+            additional_properties=(
+                create_schema(
+                    field=field.children[1],
+                    generate_examples=generate_examples,
+                    plugins=plugins,
+                    schemas=schemas,
+                    prefer_alias=prefer_alias,
+                )
+                if field.children and len(field.children) == 2
+                else None
+            ),
+        )
 
     if field.is_non_string_sequence or field.is_non_string_iterable:
         items = [


Test patch:
diff --git a/tests/openapi/test_spec_generation.py b/tests/openapi/test_spec_generation.py
--- a/tests/openapi/test_spec_generation.py
+++ b/tests/openapi/test_spec_generation.py
@@ -33,7 +33,13 @@ def handler(data: cls) -> cls:
                 "last_name": {"type": "string"},
                 "id": {"type": "string"},
                 "optional": {"oneOf": [{"type": "null"}, {"type": "string"}]},
-                "complex": {"type": "object"},
+                "complex": {
+                    "type": "object",
+                    "additionalProperties": {
+                        "type": "array",
+                        "items": {"type": "object", "additionalProperties": {"type": "string"}},
+                    },
+                },
                 "pets": {
                     "oneOf": [
                         {"type": "null"},