示例#1
0
 def test_passes_sex_parameter_to_model_correctly_when_female(self):
     self.mock_serializer.load.return_value = marshmallow.UnmarshalResult(
         data={
             "ethnicity": "black",
             "sex": "female"
         },
         errors={},
     )
     rv = self.app.get("/acceptance_probability")
     self.mock_model.predict.assert_called_once_with("women", "black")
示例#2
0
 def _do_load(self, data, many=None, partial=None, postprocess=True):
     """Override the :class:`~marshmallow.Schema`\ 's ``_do_load`` to correctly
     handle the included data."""
     many = self.many if many is None else bool(many)
     # Load the main data
     loaded, errors = super(Schema, self)._do_load(data,
                                                   many=many,
                                                   partial=partial,
                                                   postprocess=postprocess)
     objs = {}
     if many:
         for part_source, part_loaded in zip(data['data'], loaded):
             objs[(part_source['type'], part_source['id'])] = ({
                 'data':
                 part_source
             }, part_loaded)
     else:
         objs[(data['data']['type'], data['data']['id'])] = (data, loaded)
     # Load the included data
     for part_source in data['included'] if 'included' in data else []:
         if part_source['type'] in self.load_schemas:
             part_loaded, errors = super(Schema, self.load_schemas[part_source['type']]).\
                 _do_load({'data': part_source}, many=False, partial=None, postprocess=True)
             objs[(part_source['type'], part_source['id'])] = ({
                 'data':
                 part_source
             }, part_loaded)
     # Fix the relationships
     for part_source, part_loaded in objs.values():
         schema = self.load_schemas[part_source['data']['type']]
         for field_name, validator in schema.fields.items():
             if isinstance(validator, Relationship):
                 links = validator.deserialize(
                     part_source['data']['relationships'][field_name]
                     ['data'] if 'relationships' in part_source['data']
                     and field_name in part_source['data']['relationships']
                     else None)
                 if validator.many:
                     if isinstance(part_loaded, dict):
                         part_loaded[field_name] = [
                             objs[link][1] for link in links
                         ] if links else []
                     else:
                         setattr(part_loaded, field_name,
                                 [objs[link][1]
                                  for link in links]) if links else []
                 else:
                     if isinstance(part_loaded, dict):
                         part_loaded[
                             field_name] = objs[links][1] if links else {}
                     else:
                         setattr(part_loaded, field_name,
                                 objs[links][1]) if links else {}
     return ma.UnmarshalResult(loaded, errors)
示例#3
0
 def test_returns_result_of_prediction_in_response(self):
     self.mock_model.predict.return_value = 0.23
     self.mock_serializer.load.return_value = marshmallow.UnmarshalResult(
         data={
             "ethnicity": "black",
             "sex": "female"
         },
         errors={},
     )
     rv = self.app.get("/acceptance_probability")
     result = json.loads(rv.data.decode("utf-8"))
     self.assertEqual(result["value"], 0.23)
示例#4
0
    def update(self, obj, data, **kwargs):
        """Helper function to update an already existing document
    instead of creating a new one.
    :param obj: Mongoengine Document to update
    :param data: incomming payload to deserialize
    :return: an :class UnmarshallResult:

    Example: ::

        from marshmallow_mongoengine import ModelSchema
        from mymodels import User

        class UserSchema(ModelSchema):
            class Meta:
                model = User

        def update_obj(id, payload):
            user = User.objects(id=id).first()
            result = UserSchema().update(user, payload)
            result.data is user # True

    Note:

        Given the update is done on a existing object, the required param
        on the fields is ignored
        """
        # TODO: find a cleaner way to skip required validation on update
        required_fields = [k for k, f in self.fields.items() if f.required]
        for field in required_fields:
            self.fields[field].required = False
        loaded_data, errors = self._do_load(data, postprocess=False)
        for field in required_fields:
            self.fields[field].required = True
        if not errors:
            # Update the given obj fields
            for k, v in loaded_data.items():
                # Skip default values that have been automatically
                # added during unserialization
                if k in data:
                    setattr(obj, k, v)
        return ma.UnmarshalResult(data=obj, errors=errors)