nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: s-knibbs/dataclasses-jsonschema
Pull request #45 (2019-03-26 18:38:07)

Field defaults using default_factory are included in generated schema
When a default factory is used, why not writing the default into the json schema ?

Maybe I broke your convention to put the test classes into conf test. Don't hesitate to tell me, I will modify to respect it.


Patch:
diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py
index b47d2ce..b7628f0 100644
--- a/dataclasses_jsonschema/__init__.py
+++ b/dataclasses_jsonschema/__init__.py
@@ -320,8 +320,16 @@ class JsonSchemaMixin:
         default = None
         if isinstance(field, Field):
             field_type = field.type
+            default_value = None
             if field.default is not MISSING and field.default is not None:
-                default = cls._encode_field(field.type, field.default, omit_none=False)
+                # In case of default value given
+                default_value = field.default
+            elif field.default_factory is not MISSING and field.default_factory is not None:  # type: ignore
+                # In case of a default factory given, we call it
+                default_value = field.default_factory()  # type: ignore
+
+            if default_value is not None:
+                default = cls._encode_field(field.type, default_value, omit_none=False)
                 required = False
         else:
             field_type = field


Test patch:
diff --git a/tests/test_all.py b/tests/test_all.py
index 05d7d30..3fe1bf3 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -1,3 +1,5 @@
+from dataclasses import dataclass, field
+from typing import List
 from uuid import UUID
 
 from .conftest import Foo, Point, Recursive, OpaqueData, ShoppingCart, Product, ProductList, SubSchemas, Bar, Weekday, \
@@ -8,11 +10,11 @@ from dataclasses_jsonschema import SchemaType, ValidationError
 
 try:
     import valico as _
+
     have_valico = True
 except ImportError:
     have_valico = False
 
-
 FOO_SCHEMA = {
     'description': 'A foo that foos',
     'properties': {
@@ -29,7 +31,6 @@ FOO_SCHEMA = {
     'required': ['a', 'c', 'd', 'f', 'g']
 }
 
-
 SWAGGER_V2_FOO_SCHEMA = {
     'description': 'A foo that foos',
     'properties': {
@@ -142,7 +143,7 @@ ZOO_SCHEMA = {
     'type': 'object',
     'description': "A zoo",
     'properties': {
-        'animal_types': {'additionalProperties': {'type': 'string'}, 'type': 'object'}
+        'animal_types': {'additionalProperties': {'type': 'string'}, 'type': 'object', 'default': {}}
     }
 }
 BAZ_SCHEMA = {
@@ -286,3 +287,15 @@ def test_type_union_deserialise():
 
 def test_default_values():
     assert Product(name="hammer", cost=20.0) == Product.from_dict({"name": "hammer"})
+
+
+def test_default_factory():
+    @dataclass
+    class ClassTest(JsonSchemaMixin):
+        attri: List[str] = field(default_factory=lambda: ['val'])
+
+    assert 'required' not in ClassTest.json_schema().keys()
+
+    assert ClassTest().attri == ['val']
+    assert ClassTest().to_dict() == {'attri': ['val']}
+    assert ClassTest.from_dict({}).attri == ['val']
Repository: s-knibbs/dataclasses-jsonschema
Pull request #125 (2019-12-10 12:01:08)

Support calling `to_dict` on objects with unknown enum values


Patch:
diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py
index 7b141b6..f99145b 100644
--- a/dataclasses_jsonschema/__init__.py
+++ b/dataclasses_jsonschema/__init__.py
@@ -51,6 +51,10 @@ class ValidationError(Exception):
     pass
 
 
+class UnknownEnumValueError(ValueError):
+    pass
+
+
 def is_enum(field_type: Any):
     return issubclass_safe(field_type, Enum)
 
@@ -284,7 +288,11 @@ class JsonSchemaMixin:
             elif is_final(field_type):
                 def encoder(ft, val, o): return cls._encode_field(unwrap_final(ft), val, o)
             elif is_enum(field_type):
-                def encoder(_, v, __): return v.value
+                def encoder(_, v, __):
+                    try:
+                        return v.value
+                    except AttributeError as e:
+                        raise UnknownEnumValueError(f'Unknown enum value: {v}') from e
             elif field_type_name == 'Union':
                 # Attempt to encode the field with each union variant.
                 # TODO: Find a more reliable method than this since in the case 'Union[List[str], Dict[str, int]]' this
@@ -294,7 +302,7 @@ class JsonSchemaMixin:
                     try:
                         encoded = cls._encode_field(variant, value, omit_none)
                         break
-                    except (TypeError, AttributeError):
+                    except (TypeError, AttributeError, UnknownEnumValueError):
                         continue
                 if encoded is None:
                     raise TypeError("No variant of '{}' matched the type '{}'".format(field_type, type(value)))
@@ -371,7 +379,12 @@ class JsonSchemaMixin:
         """
         data = {}
         for f in self._get_fields():
-            value = self._encode_field(f.field.type, getattr(self, f.field.name), omit_none)
+            value = getattr(self, f.field.name)
+            try:
+                value = self._encode_field(f.field.type, value, omit_none)
+            except UnknownEnumValueError as e:
+                warnings.warn(str(e))
+
             if omit_none and value is None:
                 continue
             if value is NULL:


Test patch:
diff --git a/tests/test_core.py b/tests/test_core.py
index 6f31218..faa0a31 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -904,6 +904,9 @@ def test_unrecognized_enum_value():
     p = Pet.from_dict({'name': 'snakey', 'type': 'python'}, validate_enums=False)
     assert p.type == "python"
 
+    with pytest.warns(UserWarning):
+        assert p.to_dict() == {'name': 'snakey', 'type': 'python'}
+
 
 def test_inheritance_and_additional_properties_disallowed():
     @dataclass
Repository: s-knibbs/dataclasses-jsonschema
Pull request #158 (2021-02-09 14:25:17)

Handle custom formats with fastjsonschema correctly
This fixes a bug when using the fastjsonschema library with custom field formats. fastjsonschema throws an 'unknown format' error, unless the formats are supplied to `fastjsonschema.compile` separately.


Patch:
diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py
index c0c3f68..25a1a37 100644
--- a/dataclasses_jsonschema/__init__.py
+++ b/dataclasses_jsonschema/__init__.py
@@ -20,7 +20,7 @@ except ImportError:
 
 from .field_types import (  # noqa: F401
     FieldEncoder, DateFieldEncoder, DateTimeFieldEncoder, UuidField, DecimalField,
-    IPv4AddressField, IPv6AddressField, DateTimeField, UUID_REGEX
+    IPv4AddressField, IPv6AddressField, DateTimeField
 )
 from .type_defs import JsonDict, SchemaType, JsonSchemaMeta, _NULL_TYPE, NULL  # noqa: F401
 from .type_hints import get_class_type_hints
@@ -474,8 +474,14 @@ class JsonSchemaMixin:
                 # TODO: Support validating with other schema types
                 schema_validator = cls.__compiled_schema.get(SchemaOptions(DEFAULT_SCHEMA_TYPE, validate_enums))
                 if schema_validator is None:
+                    formats = {}
+                    for encoder in cls._field_encoders.values():
+                        schema = encoder.json_schema
+                        if 'pattern' in schema and 'format' in schema:
+                            formats[schema['format']] = schema['pattern']
+
                     schema_validator = fastjsonschema.compile(
-                        cls.json_schema(validate_enums=validate_enums), formats={'uuid': UUID_REGEX}
+                        cls.json_schema(validate_enums=validate_enums), formats=formats
                     )
                     cls.__compiled_schema[SchemaOptions(DEFAULT_SCHEMA_TYPE, validate_enums)] = schema_validator
                 schema_validator(data)


Test patch:
diff --git a/tests/test_core.py b/tests/test_core.py
index 2c42e0f..3e0d16e 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -978,3 +978,27 @@ def test_module_name_extension():
     schema = Pet.json_schema(embeddable=True, schema_type=SchemaType.OPENAPI_3)
     assert schema['Pet']['x-module-name'] == 'tests.test_core'
     assert schema['Pet']['properties']['type']['x-module-name'] == 'tests.test_core'
+
+
+def test_custom_format():
+    Slug = NewType('Slug', str)
+
+    class SlugField(FieldEncoder[Slug, str]):
+
+        @property
+        def json_schema(self) -> JsonDict:
+            return {
+                'type': 'string',
+                'format': 'slug',
+                'pattern': r'^[a-z0-9\-]+$',
+            }
+
+    JsonSchemaMixin.register_field_encoders({Slug: SlugField()})
+
+    @dataclass
+    class Post(JsonSchemaMixin):
+        slug: Slug
+        content: str
+
+    post = Post.from_dict({"content": "Lorem ipsum dolor ...", "slug": "some-post"})
+    assert post.slug == Slug("some-post")
Repository: s-knibbs/dataclasses-jsonschema
Pull request #169 (2021-09-29 15:53:45)

Preserve type of dict keys when converting to & from json


Patch:
diff --git a/dataclasses_jsonschema/__init__.py b/dataclasses_jsonschema/__init__.py
index 0b5c71e..e2b0d54 100644
--- a/dataclasses_jsonschema/__init__.py
+++ b/dataclasses_jsonschema/__init__.py
@@ -425,12 +425,15 @@ class JsonSchemaMixin:
         try:
             decoder = cls.__decode_cache[field_type]  # type: ignore
         except (KeyError, TypeError):
-            # Note: Only literal types composed of primitive values are currently supported
-            if type(value) in JSON_ENCODABLE_TYPES and (field_type in JSON_ENCODABLE_TYPES or is_literal(field_type)):
-                return value
             # Replace any nested dictionaries with their targets
             field_type_name = cls._get_field_type_name(field_type)
-            if cls._is_json_schema_subclass(field_type):
+            # Note: Only literal types composed of primitive values are currently supported
+            if type(value) in JSON_ENCODABLE_TYPES and (field_type in JSON_ENCODABLE_TYPES or is_literal(field_type)):
+                if is_literal(field_type):
+                    def decoder(_, __, val): return val
+                else:
+                    def decoder(_, ft, val): return ft(val)
+            elif cls._is_json_schema_subclass(field_type):
                 def decoder(_, ft, val): return ft.from_dict(val, validate=False)
             elif is_nullable(field_type):
                 def decoder(f, ft, val): return cls._decode_field(f, unwrap_nullable(ft), val)


Test patch:
diff --git a/tests/test_core.py b/tests/test_core.py
index 83f1767..41daa72 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1014,3 +1014,17 @@ def test_untyped_dict():
     example = Example.from_dict({'data': {'a': 'foo'}})
     assert example.data == {'a': 'foo'}
     assert example.to_dict() == {'data': {'a': 'foo'}}
+
+
+def test_integer_dict_keys():
+    """Tests that types for dict keys are preserved. Technically, JSON only supports strings as dictionary keys,
+    but these can be converted back to the original type using the type annotations
+    """
+
+    @dataclass
+    class Config(JsonSchemaMixin):
+        assignment: Dict[int, str]
+
+    c = Config({1: 'foo', 2: 'bar'})
+    data = c.to_json()
+    assert c == Config.from_json(data)