Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change quantity to DecimalType #21

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 29 additions & 3 deletions openregistry/api/models/ocds.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
from uuid import uuid4

from schematics.types import (StringType, FloatType, URLType, IntType,
BooleanType, BaseType, EmailType, MD5Type)
from schematics.exceptions import ValidationError
BooleanType, BaseType, EmailType, MD5Type,
DecimalType as BaseDecimalType)
from schematics.exceptions import ValidationError, ConversionError
from schematics.types.compound import ModelType, ListType
from schematics.types.serializable import serializable

from decimal import Decimal, InvalidOperation, ROUND_HALF_UP

from openregistry.api.constants import (DEFAULT_CURRENCY,
DEFAULT_ITEM_CLASSIFICATION, ITEM_CLASSIFICATIONS, DOCUMENT_TYPES,
IDENTIFIER_CODES, DEBTOR_TYPES
Expand Down Expand Up @@ -147,6 +150,29 @@ class Identifier(Model):
uri = URLType() # A URI to identify the organization.


class DecimalType(BaseDecimalType):

def __init__(self, precision=-3, **kwargs):
self.precision = Decimal("1E{:d}".format(precision))
super(DecimalType, self).__init__(**kwargs)

def to_primitive(self, value, context=None):
return value

def to_native(self, value, context=None):
try:
value = Decimal(value).quantize(self.precision, rounding=ROUND_HALF_UP).normalize()
except (TypeError, InvalidOperation):
raise ConversionError(self.messages['number_coerce'].format(value))

if self.min_value is not None and value < self.min_value:
raise ConversionError(self.messages['number_min'].format(value))
if self.max_value is not None and self.max_value < value:
raise ConversionError(self.messages['number_max'].format(value))

return value


class Item(Model):
"""A good, service, or work to be contracted."""
id = StringType(required=True, min_length=1, default=lambda: uuid4().hex)
Expand All @@ -156,7 +182,7 @@ class Item(Model):
classification = ModelType(ItemClassification)
additionalClassifications = ListType(ModelType(Classification), default=list())
unit = ModelType(Unit) # Description of the unit which the good comes in e.g. hours, kilograms
quantity = IntType() # The number of units required
quantity = DecimalType() # The number of units required
address = ModelType(Address)
location = ModelType(Location)

Expand Down
27 changes: 25 additions & 2 deletions openregistry/api/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import mock
from datetime import datetime, timedelta
from schematics.exceptions import ConversionError, ValidationError, ModelValidationError
from decimal import Decimal

from openregistry.api.utils import get_now

Expand All @@ -12,7 +13,7 @@
from openregistry.api.models.ocds import (
Organization, ContactPoint, Identifier, Address,
Item, Location, Unit, Value, ItemClassification, Classification,
Period, PeriodEndRequired, Document
Period, PeriodEndRequired, Document, DecimalType
)


Expand Down Expand Up @@ -45,6 +46,28 @@ def test_IsoDateTimeType_model(self):
with self.assertRaises(ConversionError):
dt.to_native(dt.to_primitive(date))

def test_DecimalType_model(self):
number = '5.001'

dt = DecimalType()

value = dt.to_primitive(number)
self.assertEqual(Decimal(number), dt.to_native(number))
self.assertEqual(Decimal(number), dt.to_native(value))

for number in (None, '5,5'):
with self.assertRaisesRegexp(ConversionError, u"Number '{}' failed to convert to a decimal.".format(number)):
dt.to_native(number)

dt = DecimalType(precision=-3, min_value=Decimal('0'), max_value=Decimal('10.0'))

self.assertEqual(Decimal('0.111'), dt.to_native('0.11111'))
self.assertEqual(Decimal('0.556'), dt.to_native('0.55555'))

for number in ('-1.0', '11.0'):
with self.assertRaises(ConversionError):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут треба assertRaisesRegexp

dt.to_native(dt.to_primitive(number))

def test_HashType_model(self):
from uuid import uuid4

Expand Down Expand Up @@ -263,7 +286,7 @@ def test_Item_model(self):
"name": u"item",
"code": u"39513200-3"
},
"quantity": 5,
"quantity": Decimal('5.001'),
"address": {
"countryName": u"Україна",
"postalCode": "79000",
Expand Down