Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to generate wrapper fields #982

Merged
merged 6 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/codegen/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ pass through each step before next one starts. The order of the steps is very im

- [DetectCircularReferences][xsdata.codegen.handlers.DetectCircularReferences]
- [CreateCompoundFields][xsdata.codegen.handlers.CreateCompoundFields]
- [CreateWrapperFields][xsdata.codegen.handlers.CreateWrapperFields]
- [DisambiguateChoices][xsdata.codegen.handlers.DisambiguateChoices]
- [ResetAttributeSequenceNumbers][xsdata.codegen.handlers.ResetAttributeSequenceNumbers]

Expand Down
41 changes: 41 additions & 0 deletions docs/codegen/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,47 @@ hat_or_bat_cat: list[str | int | float] = field(...)
product: list[Shoe | Shirt | Hat] = field(...)
```

### WrapperFields

Generate wrapper fields whenever possible for single or collections of simple and
complex elements.

The wrapper and wrapped elements can't be optional. If the wrapped value is a list it
must have minimum `occurs >= 1`.

```xml show_lines="2:17"
--8<-- "tests/fixtures/wrapper/schema.xsd"
```

**Default Value:** `False`

**CLI Option:** `--wrapper-fields / --no-wrapper-fields`

**Examples:**

```python
alpha: str = field(
metadata={
"wrapper": "alphas",
"type": "Element",
},
)
bravo: List[int] = field(
default_factory=list,
metadata={
"wrapper": "bravos",
"type": "Element",
},
)
charlie: List[Charlie] = field(
default_factory=list,
metadata={
"wrapper": "charlies",
"type": "Element",
},
)
```

### PostponedAnnotations

Use [PEP-563](https://peps.python.org/pep-0563/), postponed evaluation of annotations.
Expand Down
4 changes: 2 additions & 2 deletions docs/models/fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,8 +332,8 @@ declared with `init=False` or with a default value otherwise data binding will f

### `wrapper`

The element name to wrap a collection of elements or primitives, in order to avoid
having a dedicated wrapper class.
The element name to wrap a single or a collection of elements or primitives, in order to
avoid having a dedicated wrapper class.

```python
>>> from dataclasses import dataclass, field
Expand Down
123 changes: 123 additions & 0 deletions tests/codegen/handlers/test_create_wrapper_fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
from xsdata.codegen.container import ClassContainer
from xsdata.codegen.handlers import CreateWrapperFields
from xsdata.models.config import GeneratorConfig
from xsdata.models.enums import DataType, Tag
from xsdata.utils.testing import (
AttrFactory,
AttrTypeFactory,
ClassFactory,
ExtensionFactory,
FactoryTestCase,
)


class CreateWrapperFieldsTests(FactoryTestCase):
def setUp(self):
super().setUp()

self.config = GeneratorConfig()
self.config.output.wrapper_fields = True
self.container = ClassContainer(config=self.config)
self.processor = CreateWrapperFields(container=self.container)

self.target = ClassFactory.create()
self.target.attrs.append(
AttrFactory.reference("foo", name="items", tag=Tag.ELEMENT)
)

self.source = ClassFactory.create(qname="foo")
self.source.attrs.append(AttrFactory.native(DataType.STRING, name="item"))
self.container.extend([self.target, self.source])

def test_process_skip_with_config_disabled(self):
self.config.output.wrapper_fields = False
self.processor.process(self.target)
self.assertIsNone(self.target.attrs[0].wrapper)

def test_process_with_valid_attr_wrapper(self):
self.processor.process(self.target)
self.assertEqual("items", self.target.attrs[0].wrapper)

def test_process_with_forward_reference(self):
self.container.remove(self.source)
self.target.inner.append(self.source)
self.target.attrs[0].types[0].forward = True

self.processor.process(self.target)
self.assertEqual("items", self.target.attrs[0].wrapper)
self.assertFalse(self.target.attrs[0].types[0].forward)
self.assertEqual(0, len(self.target.inner))

def test_process_with_invalid_attr(self):
self.target.attrs[0].tag = Tag.EXTENSION
self.processor.process(self.target)

self.assertIsNone(self.target.attrs[0].wrapper)

def test_process_with_invalid_source(self):
self.source.extensions.append(ExtensionFactory.create())
self.processor.process(self.target)

self.assertIsNone(self.target.attrs[0].wrapper)

def test_wrap_field(self):
source = AttrFactory.create()
attr = AttrFactory.create()
wrapper = attr.local_name

self.processor.wrap_field(source, attr, False)
self.assertEqual(source.name, attr.name)
self.assertEqual(source.local_name, attr.local_name)
self.assertEqual(wrapper, attr.wrapper)

def test_validate_attr(self):
# Not an element
attr = AttrFactory.create(tag=Tag.EXTENSION)
self.assertFalse(self.processor.validate_attr(attr))

# Multiple types
attr.tag = Tag.ELEMENT
attr.types = AttrTypeFactory.list(2)
self.assertFalse(self.processor.validate_attr(attr))

# Native type
attr.types = [AttrTypeFactory.native(DataType.STRING)]
self.assertFalse(self.processor.validate_attr(attr))

# Not any of the above issues
attr.types = [AttrTypeFactory.create()]
self.assertTrue(self.processor.validate_attr(attr))

def test_validate_source(self):
source = ClassFactory.create()

# Has extensions
source.extensions = ExtensionFactory.list(1)
self.assertFalse(self.processor.validate_source(source, None))

# Has multiple attrs
source.extensions.clear()
source.attrs = AttrFactory.list(2)
self.assertFalse(self.processor.validate_source(source, None))

# Has forwarded references
source.attrs.pop(0)
source.attrs[0].tag = Tag.EXTENSION
source.attrs[0].types[0].forward = True
self.assertFalse(self.processor.validate_source(source, None))

# Namespace doesn't match
source.attrs[0].types[0].forward = False
self.assertFalse(self.processor.validate_source(source, "bar"))

# Optional
source.attrs[0].namespace = "bar"
self.assertFalse(self.processor.validate_source(source, "bar"))

# Not Element
source.attrs[0].restrictions.min_occurs = 1
self.assertFalse(self.processor.validate_source(source, "bar"))

# All rules pass
source.attrs[0].tag = Tag.ELEMENT
self.assertTrue(self.processor.validate_source(source, "bar"))
4 changes: 2 additions & 2 deletions tests/codegen/handlers/test_disambiguate_choices.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ def test_process_with_duplicate_complex_types(self):
compound = AttrFactory.any()
target = ClassFactory.create()
target.attrs.append(compound)
compound.choices.append(AttrFactory.reference(name="a", qname="myint"))
compound.choices.append(AttrFactory.reference(name="b", qname="myint"))
compound.choices.append(AttrFactory.reference(qname="myint"))
compound.choices.append(AttrFactory.reference(qname="myint"))
self.container.add(target)

self.handler.process(target)
Expand Down
1 change: 1 addition & 0 deletions tests/codegen/test_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def test_initialize(self):
60: [
"DetectCircularReferences",
"CreateCompoundFields",
"CreateWrapperFields",
"DisambiguateChoices",
"ResetAttributeSequenceNumbers",
],
Expand Down
29 changes: 22 additions & 7 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,34 @@

from lxml import etree

from xsdata.formats.dataclass.context import XmlContext
from xsdata.formats.dataclass.parsers import JsonParser, XmlParser
from xsdata.formats.dataclass.serializers import JsonSerializer, XmlSerializer
from xsdata.formats.dataclass.serializers import (
JsonSerializer,
PycodeSerializer,
XmlSerializer,
)
from xsdata.formats.dataclass.serializers.config import SerializerConfig


def validate_bindings(schema: Path, clazz: Type):
__tracebackhide__ = True

sample = schema.parent.joinpath("sample.xml")
obj = XmlParser().from_path(sample, clazz)
context = XmlContext()

config = SerializerConfig(indent=" ")
actual = JsonSerializer(config=config).render(obj)
xml_parser = XmlParser(context=context)
xml_serializer = XmlSerializer(context=context, config=config)
json_serializer = JsonSerializer(context=context, config=config)
pycode_serializer = PycodeSerializer(context=context)

obj = xml_parser.from_path(sample, clazz)

code = pycode_serializer.render(obj)
sample.with_suffix(".py").write_text(code)

actual = json_serializer.render(obj)

expected = sample.with_suffix(".json")
if expected.exists():
Expand All @@ -23,10 +39,9 @@ def validate_bindings(schema: Path, clazz: Type):
else:
expected.write_text(actual, encoding="utf-8")

config = SerializerConfig(indent=" ")
xml = XmlSerializer(config=config).render(obj)
xml = xml_serializer.render(obj)

expected.with_suffix(".xsdata.xml").write_text(xml, encoding="utf-8")

validator = etree.XMLSchema(etree.parse(str(schema)))
assert validator.validate(etree.fromstring(xml.encode())), validator.error_log

expected.with_suffix(".xsdata.xml").write_text(xml, encoding="utf-8")
33 changes: 33 additions & 0 deletions tests/fixtures/compound/sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from tests.fixtures.compound.models import Alpha
from tests.fixtures.compound.models import Bravo
from tests.fixtures.compound.models import Root


obj = Root(
alpha_or_bravo=[
Alpha(

),
Alpha(

),
Bravo(

),
Bravo(

),
Alpha(

),
Bravo(

),
Alpha(

),
Bravo(

),
]
)
2 changes: 1 addition & 1 deletion tests/fixtures/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class ChoiceType:
{"name": "float", "type": float},
{"name": "qname", "type": QName},
{"name": "union", "type": Type["UnionType"], "namespace": "foo"},
{"name": "tokens", "type": List[Decimal], "tokens": True},
{"name": "tokens", "type": List[Decimal], "tokens": True, "default_factory": list},
{
"wildcard": True,
"type": object,
Expand Down
48 changes: 48 additions & 0 deletions tests/fixtures/primer/sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from decimal import Decimal
from tests.fixtures.primer.order import Comment
from tests.fixtures.primer.order import Items
from tests.fixtures.primer.order import PurchaseOrder
from tests.fixtures.primer.order import Usaddress
from xsdata.models.datatype import XmlDate


obj = PurchaseOrder(
ship_to=Usaddress(
name='Alice Smith',
street='123 Maple Street',
city='Mill Valley',
state='CA',
zip=Decimal('90952')
),
bill_to=Usaddress(
name='Robert Smith',
street='8 Oak Avenue',
city='Old Town',
state='PA',
zip=Decimal('95819')
),
comment=Comment(
value='Hurry, my lawn is going wild!'
),
items=Items(
item=[
Items.Item(
product_name='Lawnmower',
quantity=1,
usprice=Decimal('148.95'),
comment=Comment(
value='Confirm this is electric'
),
part_num='872-AA'
),
Items.Item(
product_name='Baby Monitor',
quantity=1,
usprice=Decimal('39.98'),
ship_date=XmlDate(1999, 5, 21),
part_num='926-AA'
),
]
),
order_date=XmlDate(1999, 10, 20)
)
15 changes: 15 additions & 0 deletions tests/fixtures/wrapper/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from tests.fixtures.wrapper.models import (
Alphas,
Bravos,
Charlie,
Charlies,
Wrapper,
)

__all__ = [
"Alphas",
"Bravos",
"Charlie",
"Charlies",
"Wrapper",
]
Loading
Loading