Fix for % (percent) unit (missing unary operator "%") (#5527)

* Fix `%` (percent) unit conversions

* Add tests for percent unit

* Fix formatting
This commit is contained in:
Bobbe 2023-09-12 02:20:45 +02:00 committed by GitHub
parent 2ea3499c48
commit f11a9e97d2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 3 deletions

View File

@ -106,7 +106,7 @@ def convert_physical_value(value: str, unit: str = None, strip_units=True):
val = ureg.Quantity(value, unit)
else:
# Convert to the provided unit (may raise an exception)
val = val.to(unit)
val = val.to(ureg.Unit(unit))
# At this point we *should* have a valid pint value
# To double check, look at the maginitude
@ -134,7 +134,7 @@ def convert_physical_value(value: str, unit: str = None, strip_units=True):
# So, we ensure that it is converted to a floating point value
# If we wish to return a "raw" value, some trickery is required
if unit:
magnitude = ureg.Quantity(val.to(unit)).magnitude
magnitude = ureg.Quantity(val.to(ureg.Unit(unit))).magnitude
else:
magnitude = ureg.Quantity(val.to_base_units()).magnitude

View File

@ -144,7 +144,7 @@ class ParameterTests(TestCase):
"""Test validation of 'units' field for PartParameterTemplate"""
# Test that valid units pass
for unit in [None, '', 'mm', 'A', 'm^2', 'Pa', 'V', 'C', 'F', 'uF', 'mF', 'millifarad']:
for unit in [None, '', '%', 'mm', 'A', 'm^2', 'Pa', 'V', 'C', 'F', 'uF', 'mF', 'millifarad']:
tmp = PartParameterTemplate(name='test', units=unit)
tmp.full_clean()
@ -169,6 +169,15 @@ class ParameterTests(TestCase):
param = PartParameter(part=prt, template=template, data=value)
param.full_clean()
# Test that percent unit is working
template2 = PartParameterTemplate.objects.create(
name='My Template 2',
units='%',
)
for value in ["1", "1%", "1 percent"]:
param = PartParameter(part=prt, template=template2, data=value)
param.full_clean()
bad_values = ['3 Amps', '-3 zogs', '3.14F']
# Disable enforcing of part parameter units