Skip to content

Commit

Permalink
Merge pull request #15 from Ultimaker/cs-452-foundation-for-native-types
Browse files Browse the repository at this point in the history
Add toPlain method on fields [cs-452]
  • Loading branch information
Roel Kramer authored Oct 29, 2019
2 parents 1c58b81 + 2882566 commit c2dca8e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

# Packages
*.egg
*.eggs
*.egg-info
dist
build
Expand Down
28 changes: 26 additions & 2 deletions jsonmodels/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import re
import six
from dateutil.parser import parse
from typing import List, Optional, Dict, Set
from typing import List, Optional, Dict, Set, Union, Pattern

from .collections import ModelCollection
from .errors import RequiredFieldError, BadTypeError, AmbiguousTypeError
Expand All @@ -14,6 +14,12 @@
# it is a completely valid default value.
NotSet = object()

# BSON compatible types, which can be returned by toBsonEncodable.
BsonEncodable = Union[
float, str, object, Dict, List, bytes, bool, datetime.datetime, None,
Pattern, int, bytes
]


class BaseField(object):

Expand Down Expand Up @@ -125,8 +131,26 @@ def _get_embed_type(value, models):
return matching_models[0]
return models[0]

def toBsonEncodable(self, value: types) -> BsonEncodable:
"""Optionally return a bson encodable python object.
Returned object should be BSON compatible. By default uses the
`to_struct` method, which creates JSON compatible types. JSON is
compatible with bson, but only has support for limited types. When
required, this method should cast the value to supported bson type.
See: https://api.mongodb.com/python/current/api/bson/index.html
For example: when a value is a datetime object return it as a datetime
object. When a value is of CustomDateObject, cast it to a datetime
object before returning it.
:param value: Value
:return: a value which should be bson encodable
"""
return self.to_struct(value=value)

def to_struct(self, value):
"""Cast value to Python structure."""
"""Cast value to Python dict."""
return value

def parse_value(self, value):
Expand Down
11 changes: 11 additions & 0 deletions tests/test_plain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from unittest import mock

from jsonmodels import fields


@mock.patch('jsonmodels.fields.BaseField.to_struct')
def test_toBsonEncodable_calls_to_struct(f):
"""Test if default implementation of toBsonEncodable calls to_struct."""
field = fields.StringField()
field.toBsonEncodable(value="text")
f.assert_called_once()

0 comments on commit c2dca8e

Please sign in to comment.