Skip to content

Commit 6169811

Browse files
committed
Add writeOnly attribute for a load_only field if OpenAPI version >= 3
1 parent a245ad8 commit 6169811

2 files changed

Lines changed: 29 additions & 4 deletions

File tree

apispec/ext/marshmallow/swagger.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def field2choices(field, **kwargs):
135135
return attributes
136136

137137

138-
def field2dump_only(field, **kwargs):
138+
def field2read_only(field, **kwargs):
139139
"""Return the dictionary of swagger field attributes for a dump_only field.
140140
141141
:param Field field: A marshmallow field.
@@ -147,6 +147,18 @@ def field2dump_only(field, **kwargs):
147147
return attributes
148148

149149

150+
def field2write_only(field, **kwargs):
151+
"""Return the dictionary of swagger field attributes for a load_only field.
152+
153+
:param Field field: A marshmallow field.
154+
:rtype: dict
155+
"""
156+
attributes = {}
157+
if field.load_only and kwargs['openapi_major_version'] >= 3:
158+
attributes['writeOnly'] = True
159+
return attributes
160+
161+
150162
def field2nullable(field, **kwargs):
151163
"""Return the dictionary of swagger field attributes for a nullable field.
152164
@@ -322,7 +334,8 @@ def field2property(field, spec=None, use_refs=True, dump=True, name=None):
322334

323335
for attr_func in (
324336
field2choices,
325-
field2dump_only,
337+
field2read_only,
338+
field2write_only,
326339
field2nullable,
327340
field2range,
328341
field2length,

tests/test_swagger.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -387,20 +387,32 @@ class NotASchema(object):
387387
assert excinfo.value.args[0] == ("{0!r} doesn't have either `fields` "
388388
"or `_declared_fields`".format(NotASchema))
389389

390-
def test_dump_only_load_only_fields(self):
390+
@pytest.mark.parametrize('openapi_version', ['2.0.0', '3.0.0'])
391+
def test_dump_only_load_only_fields(self, openapi_version):
392+
spec = APISpec(
393+
title='Pets',
394+
version='0.1',
395+
plugins=['apispec.ext.marshmallow'],
396+
openapi_version=openapi_version
397+
)
398+
391399
class UserSchema(Schema):
392400
_id = fields.Str(dump_only=True)
393401
name = fields.Str()
394402
password = fields.Str(load_only=True)
395403

396-
res = swagger.schema2jsonschema(UserSchema())
404+
res = swagger.schema2jsonschema(UserSchema(), spec)
397405
props = res['properties']
398406
assert 'name' in props
399407
# dump_only field appears with readOnly attribute
400408
assert '_id' in props
401409
assert 'readOnly' in props['_id']
402410
# load_only field appears (writeOnly attribute does not exist)
403411
assert 'password' in props
412+
if openapi_version == '2.0.0':
413+
assert 'writeOnly' not in props['password']
414+
else:
415+
assert 'writeOnly' in props['password']
404416

405417

406418
class TestMarshmallowSchemaToParameters:

0 commit comments

Comments
 (0)