Skip to content

Instantly share code, notes, and snippets.

@jdevera
Created November 3, 2017 10:34
Show Gist options
  • Save jdevera/5fed8e8ee23ff71dfa0ee5d686d844fb to your computer and use it in GitHub Desktop.
Save jdevera/5fed8e8ee23ff71dfa0ee5d686d844fb to your computer and use it in GitHub Desktop.
Create a model object without validation (useful for testing) in a generated Python Swagger Client
def make_invalid_model(model_class, **kwargs):
"""
create a model object bypassing all member validation
:param model_class: the class of the generated model that needs to be instantiated
:param kwargs: all the model parameters, as they would be passed to the constructor
:return: an instance of model_class
"""
def get_default_values(model_class, attributes):
signature = inspect.signature(model_class.__init__)
default_values = {}
for attribute in attributes:
param = signature.parameters[attribute]
param_default = param.default if param.default != inspect._empty else none
default_values[attribute] = param_default
return default_values
model = model_class.__new__(model_class)
# since we are bypassing the constructor and the setters, make sure at least that the
# parameters passed correspond to those in the model.
assert set(kwargs.keys()) <= set(model_class.swagger_types.keys())
model.__dict__ = {'_' + name : value for name, value in kwargs.items()}
missing_attributes = set(model_class.swagger_types.keys()) - set(kwargs.keys())
if missing_attributes:
defaults = get_default_values(model_class, missing_attributes)
model.__dict__.update({ '_' + name : default for name, default in defaults.items()})
return model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment