test: Add tests for frappe.utils.data.cast

This commit is contained in:
Gavin D'souza 2021-08-30 18:51:36 +05:30
parent 7e2e8c87ff
commit be72397bca

View file

@ -6,12 +6,13 @@ import frappe
from frappe.utils import evaluate_filters, money_in_words, scrub_urls, get_url
from frappe.utils import validate_url, validate_email_address
from frappe.utils import ceil, floor
from frappe.utils.data import validate_python_code
from frappe.utils.data import cast, validate_python_code
from PIL import Image
from frappe.utils.image import strip_exif_data, optimize_image
import io
from mimetypes import guess_type
from datetime import datetime, timedelta, date
class TestFilters(unittest.TestCase):
def test_simple_dict(self):
@ -93,6 +94,34 @@ class TestDataManipulation(unittest.TestCase):
self.assertTrue('style="background-image: url(\'{0}/assets/frappe/bg.jpg\') !important"'.format(url) in html)
self.assertTrue('<a href="mailto:test@example.com">email</a>' in html)
class TestFieldCasting(unittest.TestCase):
def test_float_types(self):
FLOAT_TYPES = ("Currency", "Float", "Percent")
for fieldtype in FLOAT_TYPES:
self.assertIsInstance(cast(fieldtype, value=None), float)
self.assertIsInstance(cast(fieldtype, value=1.12), float)
self.assertIsInstance(cast(fieldtype, value=112), float)
def test_int_types(self):
INT_TYPES = ("Int", "Check")
for fieldtype in INT_TYPES:
self.assertIsInstance(cast(fieldtype, value=None), int)
self.assertIsInstance(cast(fieldtype, value=1.12), int)
self.assertIsInstance(cast(fieldtype, value=112), int)
def test_datetime_types(self):
self.assertIsInstance(cast("Datetime", value=None), datetime)
self.assertIsInstance(cast("Datetime", value="12-2-22"), datetime)
def test_date_types(self):
self.assertIsInstance(cast("Date", value=None), date)
self.assertIsInstance(cast("Date", value="12-12-2021"), date)
def test_time_types(self):
self.assertIsInstance(cast("Time", value=None), timedelta)
self.assertIsInstance(cast("Time", value="12:03:34"), timedelta)
class TestMathUtils(unittest.TestCase):
def test_floor(self):
from decimal import Decimal
@ -205,7 +234,6 @@ class TestImage(unittest.TestCase):
self.assertLess(len(optimized_content), len(original_content))
class TestPythonExpressions(unittest.TestCase):
def test_validation_for_good_python_expression(self):
valid_expressions = [
"foo == bar",
@ -229,4 +257,4 @@ class TestPythonExpressions(unittest.TestCase):
"oops = forgot_equals",
]
for expr in invalid_expressions:
self.assertRaises(frappe.ValidationError, validate_python_code, expr)
self.assertRaises(frappe.ValidationError, validate_python_code, expr)