summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHernan Grecco <hgrecco@gmail.com>2023-04-29 20:36:04 -0300
committerHernan Grecco <hgrecco@gmail.com>2023-04-29 20:36:04 -0300
commit10a2311992a3ad89b9968cd102edb67646a84412 (patch)
treeb36d826222c0d4079143fb4a758afb56cc5d8c2c
parentb63697287ba1e5de7300890ea4c03b8781b04863 (diff)
downloadpint-10a2311992a3ad89b9968cd102edb67646a84412.tar.gz
Run refurb --python-version 3.9 in pint/testsuite
-rw-r--r--pint/testsuite/__init__.py12
-rw-r--r--pint/testsuite/helpers.py14
-rw-r--r--pint/testsuite/test_compat_downcast.py11
-rw-r--r--pint/testsuite/test_compat_upcast.py5
-rw-r--r--pint/testsuite/test_converters.py2
-rw-r--r--pint/testsuite/test_dask.py7
-rw-r--r--pint/testsuite/test_definitions.py8
-rw-r--r--pint/testsuite/test_errors.py4
-rw-r--r--pint/testsuite/test_formatter.py4
-rw-r--r--pint/testsuite/test_infer_base_unit.py10
-rw-r--r--pint/testsuite/test_log_units.py2
-rw-r--r--pint/testsuite/test_non_int.py6
-rw-r--r--pint/testsuite/test_numpy.py4
-rw-r--r--pint/testsuite/test_quantity.py12
-rw-r--r--pint/testsuite/test_unit.py16
-rw-r--r--pint/testsuite/test_util.py8
16 files changed, 60 insertions, 65 deletions
diff --git a/pint/testsuite/__init__.py b/pint/testsuite/__init__.py
index 8c0cd09..35b0d91 100644
--- a/pint/testsuite/__init__.py
+++ b/pint/testsuite/__init__.py
@@ -3,7 +3,8 @@ import math
import os
import unittest
import warnings
-from contextlib import contextmanager
+import contextlib
+import pathlib
from pint import UnitRegistry
from pint.testsuite.helpers import PintOutputChecker
@@ -25,7 +26,7 @@ class QuantityTestCase:
cls.U_ = None
-@contextmanager
+@contextlib.contextmanager
def assert_no_warnings():
with warnings.catch_warnings():
warnings.simplefilter("error")
@@ -40,13 +41,12 @@ def testsuite():
# TESTING THE DOCUMENTATION requires pyyaml, serialize, numpy and uncertainties
if HAS_NUMPY and HAS_UNCERTAINTIES:
- try:
+ with contextlib.suppress(ImportError):
import serialize # noqa: F401
import yaml # noqa: F401
add_docs(suite)
- except ImportError:
- pass
+
return suite
@@ -98,7 +98,7 @@ def add_docs(suite):
"""
docpath = os.path.join(os.path.dirname(__file__), "..", "..", "docs")
docpath = os.path.abspath(docpath)
- if os.path.exists(docpath):
+ if pathlib.Path(docpath).exists():
checker = PintOutputChecker()
for name in (name for name in os.listdir(docpath) if name.endswith(".rst")):
file = os.path.join(docpath, name)
diff --git a/pint/testsuite/helpers.py b/pint/testsuite/helpers.py
index 4c560fb..191f4c3 100644
--- a/pint/testsuite/helpers.py
+++ b/pint/testsuite/helpers.py
@@ -1,6 +1,7 @@
import doctest
import pickle
import re
+import contextlib
import pytest
from packaging.version import parse as version_parse
@@ -41,14 +42,12 @@ class PintOutputChecker(doctest.OutputChecker):
if check:
return check
- try:
+ with contextlib.suppress(Exception):
if eval(want) == eval(got):
return True
- except Exception:
- pass
for regex in (_q_re, _sq_re):
- try:
+ with contextlib.suppress(Exception):
parsed_got = regex.match(got.replace(r"\\", "")).groupdict()
parsed_want = regex.match(want.replace(r"\\", "")).groupdict()
@@ -62,12 +61,10 @@ class PintOutputChecker(doctest.OutputChecker):
return False
return True
- except Exception:
- pass
cnt = 0
for regex in (_unit_re,):
- try:
+ with contextlib.suppress(Exception):
parsed_got, tmp = regex.subn("\1", got)
cnt += tmp
parsed_want, temp = regex.subn("\1", want)
@@ -76,9 +73,6 @@ class PintOutputChecker(doctest.OutputChecker):
if parsed_got == parsed_want:
return True
- except Exception:
- pass
-
if cnt:
# If there was any replacement, we try again the previous methods.
return self.check_output(parsed_want, parsed_got, optionflags)
diff --git a/pint/testsuite/test_compat_downcast.py b/pint/testsuite/test_compat_downcast.py
index ebb5907..4ca611d 100644
--- a/pint/testsuite/test_compat_downcast.py
+++ b/pint/testsuite/test_compat_downcast.py
@@ -1,3 +1,4 @@
+import operator
import pytest
from pint import UnitRegistry
@@ -121,10 +122,8 @@ def test_univariate_op_consistency(
@pytest.mark.parametrize(
"op, unit",
[
- pytest.param(
- lambda x, y: x * y, lambda ureg: ureg("kg m"), id="multiplication"
- ),
- pytest.param(lambda x, y: x / y, lambda ureg: ureg("m / kg"), id="division"),
+ pytest.param(operator.mul, lambda ureg: ureg("kg m"), id="multiplication"),
+ pytest.param(operator.truediv, lambda ureg: ureg("m / kg"), id="division"),
pytest.param(np.multiply, lambda ureg: ureg("kg m"), id="multiply ufunc"),
],
)
@@ -143,11 +142,11 @@ def test_bivariate_op_consistency(local_registry, q_base, op, unit, array):
"op",
[
pytest.param(
- WR2(lambda a, u: a * u),
+ WR2(operator.mul),
id="array-first",
marks=pytest.mark.xfail(reason="upstream issue numpy/numpy#15200"),
),
- pytest.param(WR2(lambda a, u: u * a), id="unit-first"),
+ pytest.param(WR2(operator.mul), id="unit-first"),
],
)
@pytest.mark.parametrize(
diff --git a/pint/testsuite/test_compat_upcast.py b/pint/testsuite/test_compat_upcast.py
index 56996b9..c8266f7 100644
--- a/pint/testsuite/test_compat_upcast.py
+++ b/pint/testsuite/test_compat_upcast.py
@@ -1,3 +1,4 @@
+import operator
import pytest
# Conditionally import NumPy and any upcast type libraries
@@ -49,9 +50,9 @@ def test_quantification(module_registry, ds):
@pytest.mark.parametrize(
"op",
[
- lambda x, y: x + y,
+ operator.add,
lambda x, y: x - (-y),
- lambda x, y: x * y,
+ operator.mul,
lambda x, y: x / (y**-1),
],
)
diff --git a/pint/testsuite/test_converters.py b/pint/testsuite/test_converters.py
index 62ffdb7..71a076f 100644
--- a/pint/testsuite/test_converters.py
+++ b/pint/testsuite/test_converters.py
@@ -69,7 +69,7 @@ class TestConverter:
@helpers.requires_numpy
def test_log_converter_inplace(self):
- arb_value = 3.14
+ arb_value = 3.13
c = LogarithmicConverter(scale=1, logbase=10, logfactor=1)
from_to = lambda value, inplace: c.from_reference(
diff --git a/pint/testsuite/test_dask.py b/pint/testsuite/test_dask.py
index f4dee6a..0e6a1cf 100644
--- a/pint/testsuite/test_dask.py
+++ b/pint/testsuite/test_dask.py
@@ -1,5 +1,6 @@
import importlib
-import os
+
+import pathlib
import pytest
@@ -135,8 +136,8 @@ def test_visualize(local_registry, dask_array):
assert res is None
# These commands only work on Unix and Windows
- assert os.path.exists("mydask.png")
- os.remove("mydask.png")
+ assert pathlib.Path("mydask.png").exists()
+ pathlib.Path("mydask.png").unlink()
def test_compute_persist_equivalent(local_registry, dask_array, numpy_array):
diff --git a/pint/testsuite/test_definitions.py b/pint/testsuite/test_definitions.py
index 2618c6e..69a337d 100644
--- a/pint/testsuite/test_definitions.py
+++ b/pint/testsuite/test_definitions.py
@@ -1,5 +1,7 @@
import pytest
+import math
+
from pint.definitions import Definition
from pint.errors import DefinitionSyntaxError
from pint.facets.nonmultiplicative.definitions import (
@@ -81,7 +83,7 @@ class TestDefinition:
assert x.reference == UnitsContainer(kelvin=1)
x = Definition.from_string(
- "turn = 6.28 * radian = _ = revolution = = cycle = _"
+ f"turn = {math.tau} * radian = _ = revolution = = cycle = _"
)
assert isinstance(x, UnitDefinition)
assert x.name == "turn"
@@ -89,7 +91,7 @@ class TestDefinition:
assert x.symbol == "turn"
assert not x.is_base
assert isinstance(x.converter, ScaleConverter)
- assert x.converter.scale == 6.28
+ assert x.converter.scale == math.tau
assert x.reference == UnitsContainer(radian=1)
with pytest.raises(ValueError):
@@ -136,7 +138,7 @@ class TestDefinition:
assert x.converter.logfactor == 1
assert x.reference == UnitsContainer()
- eulersnumber = 2.71828182845904523536028747135266249775724709369995
+ eulersnumber = math.e
x = Definition.from_string(
"neper = 1 ; logbase: %1.50f; logfactor: 0.5 = Np" % eulersnumber
)
diff --git a/pint/testsuite/test_errors.py b/pint/testsuite/test_errors.py
index 6a42eec..a045f6e 100644
--- a/pint/testsuite/test_errors.py
+++ b/pint/testsuite/test_errors.py
@@ -116,7 +116,7 @@ class TestErrors:
q2 = ureg.Quantity("1 bar")
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
- for ex in [
+ for ex in (
DefinitionSyntaxError("foo"),
RedefinitionError("foo", "bar"),
UndefinedUnitError("meter"),
@@ -125,7 +125,7 @@ class TestErrors:
Quantity("1 kg")._units, Quantity("1 s")._units
),
OffsetUnitCalculusError(q1._units, q2._units),
- ]:
+ ):
with subtests.test(protocol=protocol, etype=type(ex)):
pik = pickle.dumps(ureg.Quantity("1 foo"), protocol)
with pytest.raises(UndefinedUnitError):
diff --git a/pint/testsuite/test_formatter.py b/pint/testsuite/test_formatter.py
index 9e362fc..5a51a0a 100644
--- a/pint/testsuite/test_formatter.py
+++ b/pint/testsuite/test_formatter.py
@@ -5,13 +5,13 @@ from pint import formatting as fmt
class TestFormatter:
def test_join(self):
- for empty in (tuple(), []):
+ for empty in ((), []):
assert fmt._join("s", empty) == ""
assert fmt._join("*", "1 2 3".split()) == "1*2*3"
assert fmt._join("{0}*{1}", "1 2 3".split()) == "1*2*3"
def test_formatter(self):
- assert fmt.formatter(dict().items()) == ""
+ assert fmt.formatter({}.items()) == ""
assert fmt.formatter(dict(meter=1).items()) == "meter"
assert fmt.formatter(dict(meter=-1).items()) == "1 / meter"
assert fmt.formatter(dict(meter=-1).items(), as_ratio=False) == "meter ** -1"
diff --git a/pint/testsuite/test_infer_base_unit.py b/pint/testsuite/test_infer_base_unit.py
index f2605c6..9a27362 100644
--- a/pint/testsuite/test_infer_base_unit.py
+++ b/pint/testsuite/test_infer_base_unit.py
@@ -34,9 +34,9 @@ class TestInferBaseUnit:
ureg = UnitRegistry(non_int_type=Decimal)
QD = ureg.Quantity
- ibu_d = infer_base_unit(QD(Decimal("1"), "millimeter * nanometer"))
+ ibu_d = infer_base_unit(QD(Decimal(1), "millimeter * nanometer"))
- assert ibu_d == QD(Decimal("1"), "meter**2").units
+ assert ibu_d == QD(Decimal(1), "meter**2").units
assert all(isinstance(v, Decimal) for v in ibu_d.values())
@@ -69,9 +69,9 @@ class TestInferBaseUnit:
Q = ureg.Quantity
r = (
Q(Decimal("1000000000.0"), "m")
- * Q(Decimal("1"), "mm")
- / Q(Decimal("1"), "s")
- / Q(Decimal("1"), "ms")
+ * Q(Decimal(1), "mm")
+ / Q(Decimal(1), "s")
+ / Q(Decimal(1), "ms")
)
compact_r = r.to_compact()
expected = Q(Decimal("1000.0"), "kilometer**2 / second**2")
diff --git a/pint/testsuite/test_log_units.py b/pint/testsuite/test_log_units.py
index 2a048f6..3d1c905 100644
--- a/pint/testsuite/test_log_units.py
+++ b/pint/testsuite/test_log_units.py
@@ -56,7 +56,7 @@ class TestLogarithmicQuantity(QuantityTestCase):
# ## Test dB to dB units octave - decade
# 1 decade = log2(10) octave
helpers.assert_quantity_almost_equal(
- self.Q_(1.0, "decade"), self.Q_(math.log(10, 2), "octave")
+ self.Q_(1.0, "decade"), self.Q_(math.log2(10), "octave")
)
# ## Test dB to dB units dBm - dBu
# 0 dBm = 1mW = 1e3 uW = 30 dBu
diff --git a/pint/testsuite/test_non_int.py b/pint/testsuite/test_non_int.py
index d0b27ae..5a74a99 100644
--- a/pint/testsuite/test_non_int.py
+++ b/pint/testsuite/test_non_int.py
@@ -1093,7 +1093,7 @@ class _TestOffsetUnitMath(NonIntTypeTestCase):
else:
in1, in2 = self.kwargs["non_int_type"](in1), self.QP_(*in2)
input_tuple = in1, in2 # update input_tuple for better tracebacks
- expected_copy = expected_output[:]
+ expected_copy = expected_output.copy()
for i, mode in enumerate([False, True]):
self.ureg.autoconvert_offset_to_baseunit = mode
if expected_copy[i] == "error":
@@ -1130,14 +1130,14 @@ class _TestOffsetUnitMath(NonIntTypeTestCase):
def test_exponentiation(self, input_tuple, expected_output):
self.ureg.default_as_delta = False
in1, in2 = input_tuple
- if type(in1) is tuple and type(in2) is tuple:
+ if type(in1) is type(in2) is tuple:
in1, in2 = self.QP_(*in1), self.QP_(*in2)
elif type(in1) is not tuple and type(in2) is tuple:
in1, in2 = self.kwargs["non_int_type"](in1), self.QP_(*in2)
else:
in1, in2 = self.QP_(*in1), self.kwargs["non_int_type"](in2)
input_tuple = in1, in2
- expected_copy = expected_output[:]
+ expected_copy = expected_output.copy()
for i, mode in enumerate([False, True]):
self.ureg.autoconvert_offset_to_baseunit = mode
if expected_copy[i] == "error":
diff --git a/pint/testsuite/test_numpy.py b/pint/testsuite/test_numpy.py
index 1e0b928..0e96c77 100644
--- a/pint/testsuite/test_numpy.py
+++ b/pint/testsuite/test_numpy.py
@@ -303,7 +303,7 @@ class TestNumpyMathematicalFunctions(TestNumpyMethods):
@helpers.requires_array_function_protocol()
def test_fix(self):
- helpers.assert_quantity_equal(np.fix(3.14 * self.ureg.m), 3.0 * self.ureg.m)
+ helpers.assert_quantity_equal(np.fix(3.13 * self.ureg.m), 3.0 * self.ureg.m)
helpers.assert_quantity_equal(np.fix(3.0 * self.ureg.m), 3.0 * self.ureg.m)
helpers.assert_quantity_equal(
np.fix([2.1, 2.9, -2.1, -2.9] * self.ureg.m),
@@ -505,7 +505,7 @@ class TestNumpyMathematicalFunctions(TestNumpyMethods):
arr = np.array(range(3), dtype=float)
q = self.Q_(arr, "meter")
- for op_ in [op.pow, op.ipow, np.power]:
+ for op_ in (op.pow, op.ipow, np.power):
q_cp = copy.copy(q)
with pytest.raises(DimensionalityError):
op_(2.0, q_cp)
diff --git a/pint/testsuite/test_quantity.py b/pint/testsuite/test_quantity.py
index 18a56ab..45b163d 100644
--- a/pint/testsuite/test_quantity.py
+++ b/pint/testsuite/test_quantity.py
@@ -393,7 +393,7 @@ class TestQuantity(QuantityTestCase):
temp = (Q_(" 1 lbf*m")).to_preferred(preferred_units)
# would prefer this to be repeatable, but mip doesn't guarantee that currently
- assert temp.units in [ureg.W * ureg.s, ureg.ft * ureg.lbf]
+ assert temp.units in (ureg.W * ureg.s, ureg.ft * ureg.lbf)
temp = Q_("1 kg").to_preferred(preferred_units)
assert temp.units == ureg.slug
@@ -1661,7 +1661,7 @@ class TestOffsetUnitMath(QuantityTestCase):
else:
in1, in2 = in1, self.Q_(*in2)
input_tuple = in1, in2 # update input_tuple for better tracebacks
- expected_copy = expected[:]
+ expected_copy = expected.copy()
for i, mode in enumerate([False, True]):
self.ureg.autoconvert_offset_to_baseunit = mode
if expected_copy[i] == "error":
@@ -1695,14 +1695,14 @@ class TestOffsetUnitMath(QuantityTestCase):
def test_exponentiation(self, input_tuple, expected):
self.ureg.default_as_delta = False
in1, in2 = input_tuple
- if type(in1) is tuple and type(in2) is tuple:
+ if type(in1) is type(in2) is tuple:
in1, in2 = self.Q_(*in1), self.Q_(*in2)
elif type(in1) is not tuple and type(in2) is tuple:
in2 = self.Q_(*in2)
else:
in1 = self.Q_(*in1)
input_tuple = in1, in2
- expected_copy = expected[:]
+ expected_copy = expected.copy()
for i, mode in enumerate([False, True]):
self.ureg.autoconvert_offset_to_baseunit = mode
if expected_copy[i] == "error":
@@ -1733,7 +1733,7 @@ class TestOffsetUnitMath(QuantityTestCase):
def test_inplace_exponentiation(self, input_tuple, expected):
self.ureg.default_as_delta = False
in1, in2 = input_tuple
- if type(in1) is tuple and type(in2) is tuple:
+ if type(in1) is type(in2) is tuple:
(q1v, q1u), (q2v, q2u) = in1, in2
in1 = self.Q_(*(np.array([q1v] * 2, dtype=float), q1u))
in2 = self.Q_(q2v, q2u)
@@ -1744,7 +1744,7 @@ class TestOffsetUnitMath(QuantityTestCase):
input_tuple = in1, in2
- expected_copy = expected[:]
+ expected_copy = expected.copy()
for i, mode in enumerate([False, True]):
self.ureg.autoconvert_offset_to_baseunit = mode
in1_cp = copy.copy(in1)
diff --git a/pint/testsuite/test_unit.py b/pint/testsuite/test_unit.py
index fcfb2ed..c1a2704 100644
--- a/pint/testsuite/test_unit.py
+++ b/pint/testsuite/test_unit.py
@@ -2,6 +2,7 @@ import copy
import functools
import logging
import math
+import operator
import re
from contextlib import nullcontext as does_not_raise
@@ -193,7 +194,7 @@ class TestUnit(QuantityTestCase):
("unit", "power_ratio", "expectation", "expected_unit"),
[
("m", 2, does_not_raise(), "m**2"),
- ("m", dict(), pytest.raises(TypeError), None),
+ ("m", {}, pytest.raises(TypeError), None),
],
)
def test_unit_pow(self, unit, power_ratio, expectation, expected_unit):
@@ -283,7 +284,7 @@ class TestRegistry(QuantityTestCase):
with pytest.raises(errors.RedefinitionError):
ureg.define("meter = [length]")
with pytest.raises(TypeError):
- ureg.define(list())
+ ureg.define([])
ureg.define("degC = kelvin; offset: 273.15")
def test_define(self):
@@ -394,7 +395,7 @@ class TestRegistry(QuantityTestCase):
)
def test_parse_pretty_degrees(self):
- for exp in ["1Δ°C", "1 Δ°C", "ΔdegC", "delta_°C"]:
+ for exp in ("1Δ°C", "1 Δ°C", "ΔdegC", "delta_°C"):
assert self.ureg.parse_expression(exp) == self.Q_(
1, UnitsContainer(delta_degree_Celsius=1)
)
@@ -566,8 +567,7 @@ class TestRegistry(QuantityTestCase):
assert f3(3.0 * ureg.centimeter) == 0.03 * ureg.centimeter
assert f3(3.0 * ureg.meter) == 3.0 * ureg.centimeter
- def gfunc(x, y):
- return x + y
+ gfunc = operator.add
g0 = ureg.wraps(None, [None, None])(gfunc)
assert g0(3, 1) == 4
@@ -596,8 +596,7 @@ class TestRegistry(QuantityTestCase):
def test_wrap_referencing(self):
ureg = self.ureg
- def gfunc(x, y):
- return x + y
+ gfunc = operator.add
def gfunc2(x, y):
return x**2 + y
@@ -650,8 +649,7 @@ class TestRegistry(QuantityTestCase):
with pytest.raises(DimensionalityError):
f0b(3.0 * ureg.kilogram)
- def gfunc(x, y):
- return x / y
+ gfunc = operator.truediv
g0 = ureg.check(None, None)(gfunc)
assert g0(6, 2) == 3
diff --git a/pint/testsuite/test_util.py b/pint/testsuite/test_util.py
index 82cda7a..a61194d 100644
--- a/pint/testsuite/test_util.py
+++ b/pint/testsuite/test_util.py
@@ -120,13 +120,13 @@ class TestUnitsContainer:
UnitsContainer({"1": "2"})
d = UnitsContainer()
with pytest.raises(TypeError):
- d.__mul__(list())
+ d.__mul__([])
with pytest.raises(TypeError):
- d.__pow__(list())
+ d.__pow__([])
with pytest.raises(TypeError):
- d.__truediv__(list())
+ d.__truediv__([])
with pytest.raises(TypeError):
- d.__rtruediv__(list())
+ d.__rtruediv__([])
class TestToUnitsContainer: