Skip to content

Commit

Permalink
Merge pull request fuhrysteve#160 from ghostwheel42/pass_context_to_n…
Browse files Browse the repository at this point in the history
…ested

Pass marshmallow context into nested schema
  • Loading branch information
fuhrysteve authored Dec 2, 2021
2 parents 16cb2df + c04359d commit 45374be
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion marshmallow_jsonschema/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ def _from_nested_schema(self, obj, field):
only = field.only
exclude = field.exclude
nested_cls = nested
nested_instance = nested(only=only, exclude=exclude)
nested_instance = nested(only=only, exclude=exclude, context=obj.context)
else:
nested_cls = nested.__class__
name = nested_cls.__name__
Expand Down
26 changes: 26 additions & 0 deletions tests/test_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,32 @@ class TestSchema(Schema):
assert nested_def["properties"]["foo"]["type"] == "integer"


def test_nested_context():
class TestNestedSchema(Schema):
def __init__(self, *args, **kwargs):
if kwargs.get("context", {}).get("hide", False):
kwargs["exclude"] = ["foo"]
super().__init__(*args, **kwargs)

foo = fields.Integer(required=True)
bar = fields.Integer(required=True)

class TestSchema(Schema):
bar = fields.Nested(TestNestedSchema)

schema = TestSchema()
dumped_show = validate_and_dump(schema)

schema = TestSchema(context={"hide": True})
dumped_hide = validate_and_dump(schema)

nested_show = dumped_show["definitions"]["TestNestedSchema"]["properties"]
nested_hide = dumped_hide["definitions"]["TestNestedSchema"]["properties"]

assert "bar" in nested_show and "foo" in nested_show
assert "bar" in nested_hide and "foo" not in nested_hide


def test_list():
class ListSchema(Schema):
foo = fields.List(fields.String(), required=True)
Expand Down

0 comments on commit 45374be

Please sign in to comment.