How to use the pint.testsuite.QuantityTestCase function in Pint

To help you get started, we’ve selected a few Pint examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github hgrecco / pint / pint / testsuite / test_formatter.py View on Github external
# -*- coding: utf-8 -*-

from pint import formatting as fmt
from pint.testsuite import QuantityTestCase


class TestFormatter(QuantityTestCase):
    def test_join(self):
        for empty in (tuple(), []):
            self.assertEqual(fmt._join("s", empty), "")
        self.assertEqual(fmt._join("*", "1 2 3".split()), "1*2*3")
        self.assertEqual(fmt._join("{0}*{1}", "1 2 3".split()), "1*2*3")

    def test_formatter(self):
        self.assertEqual(fmt.formatter(dict().items()), "")
        self.assertEqual(fmt.formatter(dict(meter=1).items()), "meter")
        self.assertEqual(fmt.formatter(dict(meter=-1).items()), "1 / meter")
        self.assertEqual(
            fmt.formatter(dict(meter=-1).items(), as_ratio=False), "meter ** -1"
        )

        self.assertEqual(
            fmt.formatter(dict(meter=-1, second=-1).items(), as_ratio=False),
github hgrecco / pint / pint / testsuite / test_unit.py View on Github external
[ureg.Quantity(3.0, "kilogram")],
            ],
        )

    def test_parse_pattern_many_results_two_units(self):
        ureg = self.ureg
        self.assertEqual(
            ureg.parse_pattern("10'10 or 10'11", "{foot}'{inch}", many=True),
            [
                [ureg.Quantity(10.0, "foot"), ureg.Quantity(10.0, "inch")],
                [ureg.Quantity(10.0, "foot"), ureg.Quantity(11.0, "inch")],
            ],
        )


class TestCompatibleUnits(QuantityTestCase):
    FORCE_NDARRAY = False

    def setUp(self):
        super().setUp()
        self.ureg = UnitRegistry(force_ndarray=self.FORCE_NDARRAY)
        self.Q_ = self.ureg.Quantity
        self.U_ = self.ureg.Unit

    def _test(self, input_units):
        gd = self.ureg.get_dimensionality
        dim = gd(input_units)
        equiv = self.ureg.get_compatible_units(input_units)
        for eq in equiv:
            self.assertEqual(gd(eq), dim)
        self.assertEqual(equiv, self.ureg.get_compatible_units(dim))
github hgrecco / pint / pint / testsuite / test_quantity.py View on Github external
# Test that warning is no longer raised on first creation
        with warnings.catch_warnings():
            warnings.filterwarnings("error")
            self.Q_([])

    @helpers.requires_not_numpy()
    def test_no_ndarray_coercion_without_numpy(self):
        self.assertRaises(ValueError, self.Q_(1, "m").__array__)

    @patch("pint.compat.upcast_types", [FakeWrapper])
    def test_upcast_type_rejection_on_creation(self):
        self.assertRaises(TypeError, self.Q_, FakeWrapper(42), "m")
        self.assertEqual(FakeWrapper(self.Q_(42, "m")).q, self.Q_(42, "m"))


class TestQuantityToCompact(QuantityTestCase):
    def assertQuantityAlmostIdentical(self, q1, q2):
        self.assertEqual(q1.units, q2.units)
        self.assertAlmostEqual(q1.magnitude, q2.magnitude)

    def compareQuantity_compact(self, q, expected_compact, unit=None):
        self.assertQuantityAlmostIdentical(q.to_compact(unit=unit), expected_compact)

    def test_dimensionally_simple_units(self):
        ureg = self.ureg
        self.compareQuantity_compact(1 * ureg.m, 1 * ureg.m)
        self.compareQuantity_compact(1e-9 * ureg.m, 1 * ureg.nm)

    def test_power_units(self):
        ureg = self.ureg
        self.compareQuantity_compact(900 * ureg.m ** 2, 900 * ureg.m ** 2)
        self.compareQuantity_compact(1e7 * ureg.m ** 2, 10 * ureg.km ** 2)
github pymedusa / Medusa / ext / pint / testsuite / test_unit.py View on Github external
q = y('meter')
        self.assertIsInstance(y, UnitRegistry)

    def test_redefinition(self):
        d = self.ureg.define
        self.assertRaises(ValueError, d, 'meter = [time]')
        self.assertRaises(ValueError, d, 'kilo- = 1000')
        self.assertRaises(ValueError, d, '[speed] = [length]')

        # aliases
        self.assertIn('inch', self.ureg._units)
        self.assertRaises(ValueError, d, 'bla = 3.2 meter = inch')
        self.assertRaises(ValueError, d, 'myk- = 1000 = kilo-')


class TestConvertWithOffset(QuantityTestCase, ParameterizedTestCase):

    # The dicts in convert_with_offset are used to create a UnitsContainer.
    # We create UnitsContainer to avoid any auto-conversion of units.
    convert_with_offset = [
        (({'degC': 1}, {'degC': 1}), 10),
        (({'degC': 1}, {'kelvin': 1}), 283.15),
        (({'degC': 1}, {'degC': 1, 'millimeter': 1, 'meter': -1}), 'error'),
        (({'degC': 1}, {'kelvin': 1, 'millimeter': 1, 'meter': -1}), 283150),

        (({'kelvin': 1}, {'degC': 1}), -263.15),
        (({'kelvin': 1}, {'kelvin': 1}), 10),
        (({'kelvin': 1}, {'degC': 1, 'millimeter': 1, 'meter': -1}), 'error'),
        (({'kelvin': 1}, {'kelvin': 1, 'millimeter': 1, 'meter': -1}), 10000),

        (({'degC': 1, 'millimeter': 1, 'meter': -1}, {'degC': 1}), 'error'),
        (({'degC': 1, 'millimeter': 1, 'meter': -1}, {'kelvin': 1}), 'error'),
github pymedusa / Medusa / ext / pint / testsuite / test_quantity.py View on Github external
self.assertEqual(rx, zx, 'while testing {0}'.format(fun))
            self.assertEqual(ry, zy, 'while testing {0}'.format(fun))
            self.assertIsNot(rx, zx, 'while testing {0}'.format(fun))
            self.assertIsNot(ry, zy, 'while testing {0}'.format(fun))

    def test_quantity_float_complex(self):
        x = self.Q_(-4.2, None)
        y = self.Q_(4.2, None)
        z = self.Q_(1, 'meter')
        for fun in (float, complex):
            self.assertEqual(fun(x), fun(x.magnitude))
            self.assertEqual(fun(y), fun(y.magnitude))
            self.assertRaises(DimensionalityError, fun, z)


class TestDimensions(QuantityTestCase):

    FORCE_NDARRAY = False

    def test_get_dimensionality(self):
        get = self.ureg.get_dimensionality
        self.assertEqual(get('[time]'), UnitsContainer({'[time]': 1}))
        self.assertEqual(get(UnitsContainer({'[time]': 1})), UnitsContainer({'[time]': 1}))
        self.assertEqual(get('seconds'), UnitsContainer({'[time]': 1}))
        self.assertEqual(get(UnitsContainer({'seconds': 1})), UnitsContainer({'[time]': 1}))
        self.assertEqual(get('[speed]'), UnitsContainer({'[length]': 1, '[time]': -1}))
        self.assertEqual(get('[acceleration]'), UnitsContainer({'[length]': 1, '[time]': -2}))

    def test_dimensionality(self):
        x = self.Q_(42, 'centimeter')
        x.to_base_units()
        x = self.Q_(42, 'meter*second')
github hgrecco / pint / pint / testsuite / test_contexts.py View on Github external
        @ureg.with_context("sp")
        @ureg.check("[length]")
        def f(wl):
            return wl.to("terahertz")

        @ureg.with_context("sp")
        @ureg.check("[length]")
        def g(wl):
            return wl.to("terahertz")

        self.assertEqual(b, f(a))
        self.assertEqual(b, g(a))


class TestContextRedefinitions(QuantityTestCase):
    def test_redefine(self):
        ureg = UnitRegistry(
            """
            foo = [d] = f = foo_alias
            bar = 2 foo = b = bar_alias
            baz = 3 bar = _ = baz_alias
            asd = 4 baz

            @context c
                # Note how we're redefining a symbol, not the base name, as a
                # function of another name
                b = 5 f
            """.splitlines()
        )
        # Units that are somehow directly or indirectly defined as a function of the
        # overridden unit are also affected
github pymedusa / Medusa / ext / pint / testsuite / test_quantity.py View on Github external
DimensionalityError), op.ipow, in1_cp, in2)
            else:
                if type(expected_copy[i]) is tuple:
                    expected = self.Q_(np.array([expected_copy[i][0]]*2,
                                                dtype=np.float),
                                       expected_copy[i][1])
                    self.assertEqual(op.ipow(in1_cp, in2).units, expected.units)
                else:
                    expected = np.array([expected_copy[i]]*2, dtype=np.float)


                in1_cp = copy.copy(in1)
                self.assertQuantityAlmostEqual(op.ipow(in1_cp, in2), expected)


class TestDimensionReduction(QuantityTestCase):
    def _calc_mass(self, ureg):
        density = 3 * ureg.g / ureg.L
        volume = 32 * ureg.milliliter
        return density * volume

    def _icalc_mass(self, ureg):
        res = ureg.Quantity(3.0, 'gram/liter')
        res *= ureg.Quantity(32.0, 'milliliter')
        return res

    def test_mul_and_div_reduction(self):
        ureg = UnitRegistry(auto_reduce_dimensions=True)
        mass = self._calc_mass(ureg)
        self.assertEqual(mass.units, ureg.g)
        ureg = UnitRegistry(auto_reduce_dimensions=False)
        mass = self._calc_mass(ureg)
github pymedusa / Medusa / ext / pint / testsuite / test_umath.py View on Github external
# -*- coding: utf-8 -*-

from __future__ import division, unicode_literals, print_function, absolute_import

from pint.compat import np
from pint.testsuite import QuantityTestCase, helpers

# Following http://docs.scipy.org/doc/numpy/reference/ufuncs.html

if np:
    pi = np.pi


@helpers.requires_numpy()
class TestUFuncs(QuantityTestCase):

    FORCE_NDARRAY = True

    @property
    def qless(self):
        return np.asarray([1., 2., 3., 4.]) * self.ureg.dimensionless

    @property
    def qs(self):
        return 8 * self.ureg.J

    @property
    def q1(self):
        return np.asarray([1., 2., 3., 4.]) * self.ureg.J

    @property
github pymedusa / Medusa / ext / pint / testsuite / test_systems.py View on Github external
# -*- coding: utf-8 -*-

from __future__ import division, unicode_literals, print_function, absolute_import


from pint import UnitRegistry

from pint.testsuite import QuantityTestCase


class TestGroup(QuantityTestCase):

    def _build_empty_reg_root(self):
        ureg = UnitRegistry(None)
        grp = ureg.get_group('root')
        grp.remove_units('pi')
        grp.invalidate_members()
        return ureg, ureg.get_group('root')

    def test_units_programatically(self):
        ureg, root = self._build_empty_reg_root()
        d  = ureg._groups

        self.assertEqual(root._used_groups, set())
        self.assertEqual(root._used_by, set())
        root.add_units('meter', 'second', 'meter')
        self.assertEqual(root._unit_names, {'meter', 'second'})
github hgrecco / pint / pint / testsuite / test_pitheorem.py View on Github external
# -*- coding: utf-8 -*-

import itertools

from pint import pi_theorem
from pint.testsuite import QuantityTestCase


class TestPiTheorem(QuantityTestCase):

    FORCE_NDARRAY = False

    def test_simple(self):

        # simple movement
        with self.capture_log() as buffer:
            self.assertEqual(
                pi_theorem({"V": "m/s", "T": "s", "L": "m"}),
                [{"V": 1, "T": 1, "L": -1}],
            )

            # pendulum
            self.assertEqual(
                pi_theorem({"T": "s", "M": "grams", "L": "m", "g": "m/s**2"}),
                [{"g": 1, "T": 2, "L": -1}],