Merge pull request #460 from datastax/468

PYTHON-468 - Decimal serlz accepts primitive numeric types and tuple
This commit is contained in:
Greg Bestland
2016-01-29 13:46:31 -06:00
2 changed files with 23 additions and 2 deletions

View File

@@ -369,7 +369,7 @@ class DecimalType(_CassandraType):
try:
sign, digits, exponent = dec.as_tuple()
except AttributeError:
raise TypeError("Non-Decimal type received for Decimal value")
sign, digits, exponent = Decimal(dec).as_tuple()
unscaled = int(''.join([str(digit) for digit in digits]))
if sign:
unscaled *= -1

View File

@@ -11,7 +11,10 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from cassandra.marshal import bitlength
from cassandra.protocol import MAX_SUPPORTED_VERSION
try:
import unittest2 as unittest
@@ -24,7 +27,7 @@ from decimal import Decimal
from uuid import UUID
from cassandra.cqltypes import lookup_casstype, DecimalType, UTF8Type, DateType
from cassandra.util import OrderedMap, OrderedMapSerializedKey, sortedset, Time, Date
from cassandra.util import OrderedMapSerializedKey, sortedset, Time, Date
marshalled_value_pairs = (
# binary form, type, python native type
@@ -139,3 +142,21 @@ class UnmarshalTest(unittest.TestCase):
def test_date(self):
# separate test because it will deserialize as datetime
self.assertEqual(DateType.from_binary(DateType.to_binary(date(2015, 11, 2), 1), 1), datetime(2015, 11, 2))
def test_decimal(self):
# testing implicit numeric conversion
# int, tuple(sign, digits, exp), float
converted_types = (10001, (0, (1, 0, 0, 0, 0, 1), -3), 100.1)
if sys.version_info < (2, 7):
# Decimal in Python 2.6 does not accept floats for lossless initialization
# Just verifying expected exception here
f = converted_types[-1]
self.assertIsInstance(f, float)
self.assertRaises(TypeError, DecimalType.to_binary, f, MAX_SUPPORTED_VERSION)
converted_types = converted_types[:-1]
for proto_ver in range(1, MAX_SUPPORTED_VERSION + 1):
for n in converted_types:
expected = Decimal(n)
self.assertEqual(DecimalType.from_binary(DecimalType.to_binary(n, proto_ver), proto_ver), expected)