From 99410a2cb3601743dc7ac028d28c3e9a382f6362 Mon Sep 17 00:00:00 2001 From: Ruth Comer Date: Thu, 26 May 2022 11:10:45 +0100 Subject: [PATCH 1/8] ran unittest2pytest --- .../test__num2date_to_nearest_second.py | 17 +- cf_units/tests/integration/test_date2num.py | 9 +- cf_units/tests/integration/test_num2date.py | 6 +- cf_units/tests/integration/test_num2pydate.py | 10 +- cf_units/tests/test_unit.py | 410 +++++++++--------- .../tests/unit/test__discard_microsecond.py | 14 +- cf_units/tests/unit/test__udunits2.py | 92 ++-- cf_units/tests/unit/unit/test_Unit.py | 52 +-- cf_units/tests/unit/unit/test_as_unit.py | 10 +- 9 files changed, 314 insertions(+), 306 deletions(-) diff --git a/cf_units/tests/integration/test__num2date_to_nearest_second.py b/cf_units/tests/integration/test__num2date_to_nearest_second.py index ed50d76b..ae60e679 100644 --- a/cf_units/tests/integration/test__num2date_to_nearest_second.py +++ b/cf_units/tests/integration/test__num2date_to_nearest_second.py @@ -10,6 +10,7 @@ import cftime import numpy as np +import pytest import cf_units from cf_units import _num2date_to_nearest_second @@ -27,8 +28,8 @@ def check_dates(self, nums, units, expected, only_cftime=True): res = _num2date_to_nearest_second( num, unit, only_use_cftime_datetimes=only_cftime ) - self.assertEqual(exp, res) - self.assertIsInstance(res, type(exp)) + assert exp == res + assert isinstance(res, type(exp)) def check_timedelta(self, nums, units, expected): for num, unit, exp in zip(nums, units, expected): @@ -36,15 +37,15 @@ def check_timedelta(self, nums, units, expected): res = _num2date_to_nearest_second(num, unit) delta = res - epoch seconds = np.round(delta.seconds + (delta.microseconds / 1000000)) - self.assertEqual((delta.days, seconds), exp) + assert (delta.days, seconds) == exp def test_scalar(self): unit = cf_units.Unit("seconds since 1970-01-01", "gregorian") num = 5.0 exp = datetime.datetime(1970, 1, 1, 0, 0, 5) res = _num2date_to_nearest_second(num, unit) - self.assertEqual(exp, res) - self.assertIsInstance(res, cftime.datetime) + assert exp == res + assert isinstance(res, cftime.datetime) def test_sequence(self): unit = cf_units.Unit("seconds since 1970-01-01", "gregorian") @@ -64,7 +65,7 @@ def test_multidim_sequence(self): nums = [[20.0, 40.0, 60.0], [80, 100.0, 120.0]] exp_shape = (2, 3) res = _num2date_to_nearest_second(nums, unit) - self.assertEqual(exp_shape, res.shape) + assert exp_shape == res.shape def test_masked_ndarray(self): unit = cf_units.Unit("seconds since 1970-01-01", "gregorian") @@ -254,8 +255,8 @@ def test_fractional_second_360_day(self): def test_pydatetime_wrong_calendar(self): unit = cf_units.Unit("days since 1970-01-01", calendar="360_day") - with self.assertRaisesRegex( - ValueError, "illegal calendar or reference date" + with pytest.raises( + ValueError, match="illegal calendar or reference date" ): _num2date_to_nearest_second( 1, diff --git a/cf_units/tests/integration/test_date2num.py b/cf_units/tests/integration/test_date2num.py index 7905c31e..1763e285 100644 --- a/cf_units/tests/integration/test_date2num.py +++ b/cf_units/tests/integration/test_date2num.py @@ -9,6 +9,7 @@ import unittest import numpy as np +import pytest from cf_units import date2num @@ -24,7 +25,7 @@ def test_single(self): res = date2num(date, self.unit, self.calendar) # num2date won't return an exact value representing the date, # even if one exists - self.assertAlmostEqual(exp, res, places=4) + assert round(abs(exp - res), 4) == 0 def test_sequence(self): dates = [ @@ -53,21 +54,21 @@ def test_multidim_sequence(self): ] exp_shape = (2, 3) res = date2num(dates, self.unit, self.calendar) - self.assertEqual(exp_shape, res.shape) + assert exp_shape == res.shape def test_discard_mircosecond(self): date = datetime.datetime(1970, 1, 1, 0, 0, 5, 750000) exp = 5.0 res = date2num(date, self.unit, self.calendar) - self.assertAlmostEqual(exp, res, places=4) + assert round(abs(exp - res), 4) == 0 def test_long_time_interval(self): # This test should fail with an error that we need to catch properly. unit = "years since 1970-01-01" date = datetime.datetime(1970, 1, 1, 0, 0, 5) exp_emsg = 'interval of "months", "years" .* got "years".' - with self.assertRaisesRegex(ValueError, exp_emsg): + with pytest.raises(ValueError, match=exp_emsg): date2num(date, unit, self.calendar) diff --git a/cf_units/tests/integration/test_num2date.py b/cf_units/tests/integration/test_num2date.py index 1dbcf166..1f2b7ace 100644 --- a/cf_units/tests/integration/test_num2date.py +++ b/cf_units/tests/integration/test_num2date.py @@ -7,13 +7,15 @@ import unittest +import pytest + from cf_units import num2date class Test(unittest.TestCase): def test_num2date_wrong_calendar(self): - with self.assertRaisesRegex( - ValueError, "illegal calendar or reference date" + with pytest.raises( + ValueError, match="illegal calendar or reference date" ): num2date( 1, diff --git a/cf_units/tests/integration/test_num2pydate.py b/cf_units/tests/integration/test_num2pydate.py index 257b21f4..302e5418 100644 --- a/cf_units/tests/integration/test_num2pydate.py +++ b/cf_units/tests/integration/test_num2pydate.py @@ -8,6 +8,8 @@ import datetime import unittest +import pytest + from cf_units import num2pydate @@ -15,12 +17,12 @@ class Test(unittest.TestCase): def test_num2pydate_simple(self): result = num2pydate(1, "days since 1970-01-01", calendar="standard") expected = datetime.datetime(1970, 1, 2) - self.assertEqual(result, expected) - self.assertIsInstance(result, datetime.datetime) + assert result == expected + assert isinstance(result, datetime.datetime) def test_num2pydate_wrong_calendar(self): - with self.assertRaisesRegex( - ValueError, "illegal calendar or reference date" + with pytest.raises( + ValueError, match="illegal calendar or reference date" ): num2pydate(1, "days since 1970-01-01", calendar="360_day") diff --git a/cf_units/tests/test_unit.py b/cf_units/tests/test_unit.py index 82333312..9d1c7794 100644 --- a/cf_units/tests/test_unit.py +++ b/cf_units/tests/test_unit.py @@ -17,6 +17,7 @@ import cftime import numpy as np +import pytest import cf_units as unit from cf_units import suppress_errors @@ -29,36 +30,36 @@ def test_is_valid_unit_string(self): unit_strs = [" meter", "meter ", " meter "] for unit_str in unit_strs: u = Unit(unit_str) - self.assertEqual(u.name, "meter") + assert u.name == "meter" def test_not_valid_unit_str(self): - with self.assertRaisesRegex(ValueError, "Failed to parse unit"): + with pytest.raises(ValueError, match="Failed to parse unit"): Unit("wibble") def test_calendar(self): calendar = unit.CALENDAR_365_DAY u = Unit("hours since 1970-01-01 00:00:00", calendar=calendar) - self.assertEqual(u.calendar, calendar) + assert u.calendar == calendar def test_calendar_alias(self): calendar = unit.CALENDAR_NO_LEAP u = Unit("hours since 1970-01-01 00:00:00", calendar=calendar) - self.assertEqual(u.calendar, unit.CALENDAR_365_DAY) + assert u.calendar == unit.CALENDAR_365_DAY def test_no_calendar(self): u = Unit("hours since 1970-01-01 00:00:00") - self.assertEqual(u.calendar, unit.CALENDAR_STANDARD) + assert u.calendar == unit.CALENDAR_STANDARD def test_unsupported_calendar(self): - with self.assertRaisesRegex(ValueError, "unsupported calendar"): + with pytest.raises(ValueError, match="unsupported calendar"): Unit("hours since 1970-01-01 00:00:00", calendar="wibble") def test_calendar_w_unicode(self): calendar = unit.CALENDAR_365_DAY u = Unit("hours\xb2 hours-1 since epoch", calendar=calendar) - self.assertEqual(u.calendar, calendar) + assert u.calendar == calendar expected = "hours² hours-1 since 1970-01-01 00:00:00" - self.assertEqual(u.origin, expected) + assert u.origin == expected def test_unicode_valid(self): # Some unicode characters are allowed. @@ -72,183 +73,183 @@ def test_py2k_unicode(self): def test_unicode_invalid(self): # Not all unicode characters are allowed. msg = r"Failed to parse unit \"ø\"" - with self.assertRaisesRegex(ValueError, msg): + with pytest.raises(ValueError, match=msg): Unit("ø") class Test_modulus(unittest.TestCase): def test_modulus__degrees(self): u = Unit("degrees") - self.assertEqual(u.modulus, 360.0) + assert u.modulus == 360.0 def test_modulus__radians(self): u = Unit("radians") - self.assertEqual(u.modulus, np.pi * 2) + assert u.modulus == np.pi * 2 def test_no_modulus(self): u = Unit("meter") - self.assertEqual(u.modulus, None) + assert u.modulus is None class Test_is_convertible(unittest.TestCase): def test_convert_distance_to_force(self): u = Unit("meter") v = Unit("newton") - self.assertFalse(u.is_convertible(v)) + assert not u.is_convertible(v) def test_convert_distance_units(self): u = Unit("meter") v = Unit("mile") - self.assertTrue(u.is_convertible(v)) + assert u.is_convertible(v) def test_convert_to_unknown(self): u = Unit("meter") v = Unit("unknown") - self.assertFalse(u.is_convertible(v)) - self.assertFalse(v.is_convertible(u)) + assert not u.is_convertible(v) + assert not v.is_convertible(u) def test_convert_to_no_unit(self): u = Unit("meter") v = Unit("no unit") - self.assertFalse(u.is_convertible(v)) - self.assertFalse(v.is_convertible(u)) + assert not u.is_convertible(v) + assert not v.is_convertible(u) def test_convert_unknown_to_no_unit(self): u = Unit("unknown") v = Unit("no unit") - self.assertFalse(u.is_convertible(v)) - self.assertFalse(v.is_convertible(u)) + assert not u.is_convertible(v) + assert not v.is_convertible(u) class Test_is_dimensionless(unittest.TestCase): def test_dimensionless(self): u = Unit("1") - self.assertTrue(u.is_dimensionless()) + assert u.is_dimensionless() def test_distance_dimensionless(self): u = Unit("meter") - self.assertFalse(u.is_dimensionless()) + assert not u.is_dimensionless() def test_unknown_dimensionless(self): u = Unit("unknown") - self.assertFalse(u.is_dimensionless()) + assert not u.is_dimensionless() def test_no_unit_dimensionless(self): u = Unit("no unit") - self.assertFalse(u.is_dimensionless()) + assert not u.is_dimensionless() class Test_format(unittest.TestCase): def test_basic(self): u = Unit("watt") - self.assertEqual(u.format(), "W") + assert u.format() == "W" def test_format_ascii(self): u = Unit("watt") - self.assertEqual(u.format(unit.UT_ASCII), "W") + assert u.format(unit.UT_ASCII) == "W" def test_format_ut_names(self): u = Unit("watt") - self.assertEqual(u.format(unit.UT_NAMES), "watt") + assert u.format(unit.UT_NAMES) == "watt" def test_format_unit_definition(self): u = Unit("watt") - self.assertEqual(u.format(unit.UT_DEFINITION), "m2.kg.s-3") + assert u.format(unit.UT_DEFINITION) == "m2.kg.s-3" def test_format_multiple_options(self): u = Unit("watt") - self.assertEqual( - u.format([unit.UT_NAMES, unit.UT_DEFINITION]), - "meter^2-kilogram-second^-3", + assert ( + u.format([unit.UT_NAMES, unit.UT_DEFINITION]) + == "meter^2-kilogram-second^-3" ) def test_format_multiple_options_utf8(self): u = Unit("watt") - self.assertEqual( - u.format([unit.UT_NAMES, unit.UT_DEFINITION, unit.UT_UTF8]), - "meter²·kilogram·second⁻³", + assert ( + u.format([unit.UT_NAMES, unit.UT_DEFINITION, unit.UT_UTF8]) + == "meter²·kilogram·second⁻³" ) def test_format_unknown(self): u = Unit("?") - self.assertEqual(u.format(), "unknown") + assert u.format() == "unknown" def test_format_no_unit(self): u = Unit("nounit") - self.assertEqual(u.format(), "no_unit") + assert u.format() == "no_unit" def test_format_names_utf8(self): u = Unit("m2") - self.assertEqual(u.format([unit.UT_UTF8, unit.UT_NAMES]), "meter²") + assert u.format([unit.UT_UTF8, unit.UT_NAMES]) == "meter²" def test_format_latin1(self): u = Unit("m2") - self.assertEqual(u.format(unit.UT_LATIN1), "m²") + assert u.format(unit.UT_LATIN1) == "m²" class Test_name(unittest.TestCase): def test_basic(self): u = Unit("newton") - self.assertEqual(u.name, "newton") + assert u.name == "newton" def test_unknown(self): u = Unit("unknown") - self.assertEqual(u.name, "unknown") + assert u.name == "unknown" def test_no_unit(self): u = Unit("no unit") - self.assertEqual(u.name, "no_unit") + assert u.name == "no_unit" class Test_symbol(unittest.TestCase): def test_basic(self): u = Unit("joule") - self.assertEqual(u.symbol, "J") + assert u.symbol == "J" def test_unknown(self): u = Unit("unknown") - self.assertEqual(u.symbol, unit._UNKNOWN_UNIT_SYMBOL) + assert u.symbol == unit._UNKNOWN_UNIT_SYMBOL def test_no_unit(self): u = Unit("no unit") - self.assertEqual(u.symbol, unit._NO_UNIT_SYMBOL) + assert u.symbol == unit._NO_UNIT_SYMBOL class Test_definition(unittest.TestCase): def test_basic(self): u = Unit("joule") - self.assertEqual(u.definition, "m2.kg.s-2") + assert u.definition == "m2.kg.s-2" def test_unknown(self): u = Unit("unknown") - self.assertEqual(u.definition, unit._UNKNOWN_UNIT_SYMBOL) + assert u.definition == unit._UNKNOWN_UNIT_SYMBOL def test_no_unit(self): u = Unit("no unit") - self.assertEqual(u.definition, unit._NO_UNIT_SYMBOL) + assert u.definition == unit._NO_UNIT_SYMBOL class Test__apply_offset(unittest.TestCase): def test_add_integer_offset(self): u = Unit("meter") - self.assertEqual(u + 10, "m @ 10") + assert u + 10 == "m @ 10" def test_add_float_offset(self): u = Unit("meter") - self.assertEqual(u + 100.0, "m @ 100") + assert u + 100.0 == "m @ 100" def test_not_numerical_offset(self): u = Unit("meter") - with self.assertRaisesRegex(TypeError, "unsupported operand type"): + with pytest.raises(TypeError, match="unsupported operand type"): operator.add(u, "not_a_number") def test_unit_unknown(self): u = Unit("unknown") - self.assertEqual(u + 10, "unknown") + assert u + 10 == "unknown" def test_no_unit(self): u = Unit("no unit") - with self.assertRaisesRegex(ValueError, "Cannot offset"): + with pytest.raises(ValueError, match="Cannot offset"): operator.add(u, 10) @@ -256,48 +257,48 @@ class Test_offset_by_time(unittest.TestCase): def test_offset(self): u = Unit("hour") v = u.offset_by_time(unit.encode_time(2007, 1, 15, 12, 6, 0)) - self.assertEqual(v, "(3600 s) @ 20070115T120600.00000000 UTC") + assert v == "(3600 s) @ 20070115T120600.00000000 UTC" def test_not_numerical_offset(self): u = Unit("hour") - with self.assertRaisesRegex(TypeError, "numeric type"): + with pytest.raises(TypeError, match="numeric type"): u.offset_by_time("not_a_number") def test_not_time_unit(self): u = Unit("mile") - with self.assertRaisesRegex(ValueError, "Failed to offset"): + with pytest.raises(ValueError, match="Failed to offset"): u.offset_by_time(10) def test_unit_unknown(self): u = Unit("unknown") emsg = "Failed to offset" - with self.assertRaisesRegex(ValueError, emsg), suppress_errors(): + with pytest.raises(ValueError, match=emsg), suppress_errors(): u.offset_by_time(unit.encode_time(1970, 1, 1, 0, 0, 0)) def test_no_unit(self): u = Unit("no unit") emsg = "Failed to offset" - with self.assertRaisesRegex(ValueError, emsg), suppress_errors(): + with pytest.raises(ValueError, match=emsg), suppress_errors(): u.offset_by_time(unit.encode_time(1970, 1, 1, 0, 0, 0)) class Test_invert(unittest.TestCase): def test_basic(self): u = Unit("newton") - self.assertEqual(u.invert(), "m-1.kg-1.s2") + assert u.invert() == "m-1.kg-1.s2" def test_double_invert(self): # Double-inverting a unit should take you back to where you started. u = Unit("newton") - self.assertEqual(u.invert().invert(), u) + assert u.invert().invert() == u def test_invert_unknown(self): u = Unit("unknown") - self.assertEqual(u.invert(), u) + assert u.invert() == u def test_invert_no_unit(self): u = Unit("no unit") - with self.assertRaisesRegex(ValueError, "Cannot invert"): + with pytest.raises(ValueError, match="Cannot invert"): u.invert() @@ -307,105 +308,105 @@ def setUp(self): def test_square_root(self): u = Unit("volt^2") - self.assertEqual(u.root(2), "V") + assert u.root(2) == "V" def test_square_root_integer_float(self): u = Unit("volt^2") - self.assertEqual(u.root(2.0), "V") + assert u.root(2.0) == "V" def test_not_numeric(self): u = Unit("volt") - with self.assertRaisesRegex(TypeError, "numeric type"): + with pytest.raises(TypeError, match="numeric type"): u.offset_by_time("not_a_number") def test_not_integer(self): u = Unit("volt") - with self.assertRaisesRegex(TypeError, "integer .* required"): + with pytest.raises(TypeError, match="integer .* required"): u.root(1.2) def test_meaningless_operation(self): u = Unit("volt") emsg = "UT_MEANINGLESS" - with self.assertRaisesRegex(ValueError, emsg), suppress_errors(): + with pytest.raises(ValueError, match=emsg), suppress_errors(): u.root(2) def test_unit_unknown(self): u = Unit("unknown") - self.assertEqual(u.root(2), u) + assert u.root(2) == u def test_no_unit(self): u = Unit("no unit") - with self.assertRaisesRegex(ValueError, "Cannot take the root"): + with pytest.raises(ValueError, match="Cannot take the root"): u.root(2) class Test_log(unittest.TestCase): def test_base_2(self): u = Unit("hPa") - self.assertEqual(u.log(2), "lb(re 100 Pa)") + assert u.log(2) == "lb(re 100 Pa)" def test_base_10(self): u = Unit("hPa") - self.assertEqual(u.log(10), "lg(re 100 Pa)") + assert u.log(10) == "lg(re 100 Pa)" def test_negative(self): u = Unit("hPa") msg = re.escape("Failed to calculate logorithmic base of Unit('hPa')") - with self.assertRaisesRegex(ValueError, msg): + with pytest.raises(ValueError, match=msg): u.log(-1) def test_not_numeric(self): u = Unit("hPa") - with self.assertRaisesRegex(TypeError, "numeric type"): + with pytest.raises(TypeError, match="numeric type"): u.log("not_a_number") def test_unit_unknown(self): u = Unit("unknown") - self.assertEqual(u.log(10), u) + assert u.log(10) == u def test_no_unit(self): u = Unit("no unit") emsg = "Cannot take the logarithm" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): u.log(10) class Test_multiply(unittest.TestCase): def test_multiply_by_int(self): u = Unit("amp") - self.assertEqual((u * 10).format(), "10 A") + assert (u * 10).format() == "10 A" def test_multiply_by_float(self): u = Unit("amp") - self.assertEqual((u * 100.0).format(), "100 A") + assert (u * 100.0).format() == "100 A" def test_multiply_electrical_units(self): u = Unit("amp") v = Unit("volt") - self.assertEqual((u * v).format(), "W") + assert (u * v).format() == "W" def test_multiply_not_numeric(self): u = Unit("amp") - with self.assertRaisesRegex(ValueError, "Failed to parse unit"): + with pytest.raises(ValueError, match="Failed to parse unit"): operator.mul(u, "not_a_number") def test_multiply_with_unknown_unit(self): u = Unit("unknown") v = Unit("meters") - self.assertTrue((u * v).is_unknown()) - self.assertTrue((v * u).is_unknown()) + assert (u * v).is_unknown() + assert (v * u).is_unknown() def test_multiply_with_no_unit(self): u = Unit("meters") v = Unit("no unit") - with self.assertRaisesRegex(ValueError, "Cannot multiply"): + with pytest.raises(ValueError, match="Cannot multiply"): operator.mul(u, v) operator.mul(v, u) def test_multiply_unknown_and_no_unit(self): u = Unit("unknown") v = Unit("no unit") - with self.assertRaisesRegex(ValueError, "Cannot multiply"): + with pytest.raises(ValueError, match="Cannot multiply"): operator.mul(u, v) operator.mul(v, u) @@ -413,39 +414,39 @@ def test_multiply_unknown_and_no_unit(self): class Test_divide(unittest.TestCase): def test_divide_by_int(self): u = Unit("watts") - self.assertEqual((u / 10).format(), "0.1 W") + assert (u / 10).format() == "0.1 W" def test_divide_by_float(self): u = Unit("watts") - self.assertEqual((u / 100.0).format(), "0.01 W") + assert (u / 100.0).format() == "0.01 W" def test_divide_electrical_units(self): u = Unit("watts") v = Unit("volts") - self.assertEqual((u / v).format(), "A") + assert (u / v).format() == "A" def test_divide_not_numeric(self): u = Unit("watts") - with self.assertRaisesRegex(ValueError, "Failed to parse unit"): + with pytest.raises(ValueError, match="Failed to parse unit"): truediv(u, "not_a_number") def test_divide_with_unknown_unit(self): u = Unit("unknown") v = Unit("meters") - self.assertTrue((u / v).is_unknown()) - self.assertTrue((v / u).is_unknown()) + assert (u / v).is_unknown() + assert (v / u).is_unknown() def test_divide_with_no_unit(self): u = Unit("meters") v = Unit("no unit") - with self.assertRaisesRegex(ValueError, "Cannot divide"): + with pytest.raises(ValueError, match="Cannot divide"): truediv(u, v) truediv(v, u) def test_divide_unknown_and_no_unit(self): u = Unit("unknown") v = Unit("no unit") - with self.assertRaisesRegex(ValueError, "Cannot divide"): + with pytest.raises(ValueError, match="Cannot divide"): truediv(u, v) truediv(v, u) @@ -453,43 +454,46 @@ def test_divide_unknown_and_no_unit(self): class Test_power(unittest.TestCase): def test_basic(self): u = Unit("m^2") - self.assertEqual(u**0.5, Unit("m")) + assert u**0.5 == Unit("m") def test_integer_power(self): u = Unit("amp") - self.assertEqual(u**2, Unit("A^2")) + assert u**2 == Unit("A^2") def test_float_power(self): u = Unit("amp") - self.assertEqual(u**3.0, Unit("A^3")) + assert u**3.0 == Unit("A^3") def test_dimensionless(self): u = Unit("1") - self.assertEqual(u**2, u) + assert u**2 == u def test_power(self): u = Unit("amp") - self.assertRaises(TypeError, operator.pow, u, Unit("m")) - self.assertRaises(TypeError, operator.pow, u, Unit("unknown")) - self.assertRaises(TypeError, operator.pow, u, Unit("no unit")) + with pytest.raises(TypeError): + operator.pow(u, Unit("m")) + with pytest.raises(TypeError): + operator.pow(u, Unit("unknown")) + with pytest.raises(TypeError): + operator.pow(u, Unit("no unit")) def test_not_numeric(self): u = Unit("m^2") emsg = "numeric value is required" - with self.assertRaisesRegex(TypeError, emsg): + with pytest.raises(TypeError, match=emsg): operator.pow(u, "not_a_number") def test_bad_power(self): u = Unit("m^2") emsg = "Cannot raise .* by a decimal" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): operator.pow(u, 0.4) def test_unit_power(self): u = Unit("amp") v = Unit("m") emsg = "argument must be a string or a (real |)number" - with self.assertRaisesRegex(TypeError, emsg): + with pytest.raises(TypeError, match=emsg): operator.pow(u, v) @@ -498,23 +502,23 @@ def setUp(self): self.u = Unit("unknown") def test_integer_power(self): - self.assertEqual(self.u**2, Unit("unknown")) + assert self.u**2 == Unit("unknown") def test_float_power(self): - self.assertEqual(self.u**3.0, Unit("unknown")) + assert self.u**3.0 == Unit("unknown") def test_not_numeric(self): emsg = "numeric value is required" - with self.assertRaisesRegex(TypeError, emsg): + with pytest.raises(TypeError, match=emsg): operator.pow(self.u, "not_a_number") def test_bad_power(self): - self.assertEqual(self.u**0.4, self.u) + assert self.u**0.4 == self.u def test_unit_power(self): v = Unit("m") emsg = "argument must be a string or a (real |)number" - with self.assertRaisesRegex(TypeError, emsg): + with pytest.raises(TypeError, match=emsg): operator.pow(self.u, v) @@ -524,134 +528,134 @@ def setUp(self): def test_integer_power(self): emsg = "Cannot raise .* a 'no-unit'" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): operator.pow(self.u, 2) def test_float_power(self): emsg = "Cannot raise .* a 'no-unit'" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): operator.pow(self.u, 3.0) def test_not_numeric(self): emsg = "numeric value is required" - with self.assertRaisesRegex(TypeError, emsg): + with pytest.raises(TypeError, match=emsg): operator.pow(self.u, "not_a_number") def test_bad_power(self): emsg = "Cannot raise .* a 'no-unit'" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): operator.pow(self.u, 0.4) def test_unit_power(self): v = Unit("m") emsg = "argument must be a string or a (real |)number" - with self.assertRaisesRegex(TypeError, emsg): + with pytest.raises(TypeError, match=emsg): operator.pow(self.u, v) class Test_copy(unittest.TestCase): def test_basic(self): u = Unit("joule") - self.assertEqual(copy.copy(u), u) + assert copy.copy(u) == u def test_unit_unknown(self): u = Unit("unknown") - self.assertEqual(copy.copy(u), u) - self.assertTrue(copy.copy(u).is_unknown()) + assert copy.copy(u) == u + assert copy.copy(u).is_unknown() def test_no_unit(self): u = Unit("no unit") - self.assertEqual(copy.copy(u), u) - self.assertTrue(copy.copy(u).is_no_unit()) + assert copy.copy(u) == u + assert copy.copy(u).is_no_unit() class Test_stringify(unittest.TestCase): def test___str__(self): u = Unit("meter") - self.assertEqual(str(u), "meter") + assert str(u) == "meter" def test___repr___basic(self): u = Unit("meter") - self.assertEqual(repr(u), "Unit('meter')") + assert repr(u) == "Unit('meter')" def test___repr___time_unit(self): u = Unit( "hours since 2007-01-15 12:06:00", calendar=unit.CALENDAR_GREGORIAN ) exp = "Unit('hours since 2007-01-15 12:06:00', calendar='standard')" - self.assertEqual(repr(u), exp) + assert repr(u) == exp class Test_equality(unittest.TestCase): def test_basic(self): u = Unit("meter") - self.assertEqual(u, "meter") + assert u == "meter" def test_equivalent_units(self): u = Unit("meter") v = Unit("m.s-1") w = Unit("hertz") - self.assertEqual(u, v / w) + assert u == v / w def test_non_equivalent_units(self): u = Unit("meter") v = Unit("amp") - self.assertNotEqual(u, v) + assert u != v def test_eq_cross_category(self): m = Unit("meter") u = Unit("unknown") n = Unit("no_unit") - self.assertNotEqual(m, u) - self.assertNotEqual(m, n) + assert m != u + assert m != n def test_unknown(self): u = Unit("unknown") - self.assertEqual(u, "unknown") + assert u == "unknown" def test_no_unit(self): u = Unit("no_unit") - self.assertEqual(u, "no_unit") + assert u == "no_unit" def test_unknown_no_unit(self): u = Unit("unknown") v = Unit("no_unit") - self.assertNotEqual(u, v) + assert u != v def test_not_implemented(self): u = Unit("meter") - self.assertFalse(u == {}) + assert not (u == {}) class Test_non_equality(unittest.TestCase): def test_basic(self): u = Unit("meter") - self.assertFalse(u != "meter") + assert not (u != "meter") def test_non_equivalent_units(self): u = Unit("meter") v = Unit("amp") - self.assertNotEqual(u, v) + assert u != v def test_ne_cross_category(self): m = Unit("meter") u = Unit("unknown") n = Unit("no_unit") - self.assertNotEqual(m, u) - self.assertNotEqual(m, n) - self.assertNotEqual(u, n) + assert m != u + assert m != n + assert u != n def test_unknown(self): u = Unit("unknown") - self.assertFalse(u != "unknown") + assert not (u != "unknown") def test_no_unit(self): u = Unit("no_unit") - self.assertFalse(u != "no_unit") + assert not (u != "no_unit") def test_not_implemented(self): u = Unit("meter") - self.assertNotEqual(u, {}) + assert u != {} class Test_convert(unittest.TestCase): @@ -660,14 +664,14 @@ def test_convert_float(self): v = Unit("mile") result = u.convert(1609.344, v) expected = 1.0 - self.assertEqual(result, expected) + assert result == expected def test_convert_int(self): u = Unit("mile") v = Unit("meter") result = u.convert(1, v) expected = 1609.344 - self.assertEqual(result, expected) + assert result == expected def test_convert_array(self): u = Unit("meter") @@ -687,7 +691,7 @@ def test_incompatible_units(self): u = Unit("m") v = Unit("V") emsg = "Unable to convert" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): u.convert(1.0, v) def test_unknown_units(self): @@ -696,11 +700,11 @@ def test_unknown_units(self): m = Unit("m") val = 1.0 emsg = "Unable to convert" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): u.convert(val, m) - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): m.convert(val, u) - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): u.convert(val, v) def test_no_units(self): @@ -709,11 +713,11 @@ def test_no_units(self): m = Unit("m") val = 1.0 emsg = "Unable to convert" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): u.convert(val, m) - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): m.convert(val, u) - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): u.convert(val, v) def test_convert_time_units(self): @@ -729,7 +733,7 @@ def test_incompatible_time_units(self): v = Unit("seconds since 1979-04-01 00:00:00", calendar="gregorian") u1point = np.array([54432000.0], dtype=np.float32) emsg = "Unable to convert" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): u.convert(u1point, v) @@ -739,13 +743,13 @@ def test(self): u = Unit("unknown") n = Unit("no_unit") start = [m, u, n] - self.assertEqual(sorted(start), [m, n, u]) + assert sorted(start) == [m, n, u] class Test_is_unknown(unittest.TestCase): def _check(self, unknown_str): u = Unit(unknown_str) - self.assertTrue(u.is_unknown()) + assert u.is_unknown() def test_unknown_representations(self): representations = ["unknown", "?", "???"] @@ -754,23 +758,23 @@ def test_unknown_representations(self): def test_no_unit(self): u = Unit("no unit") - self.assertFalse(u.is_unknown()) + assert not u.is_unknown() def test_known_unit(self): u = Unit("meters") - self.assertFalse(u.is_unknown()) + assert not u.is_unknown() def test_no_ut_pointer(self): # Test that a unit that was poorly constructed has a # degree of tolerance by making it unknown. # https://github.com/SciTools/cf-units/issues/133 refers. - self.assertTrue(Unit.__new__(Unit).is_unknown()) + assert Unit.__new__(Unit).is_unknown() class Test_is_no_unit(unittest.TestCase): def _check(self, no_unit_str): u = Unit(no_unit_str) - self.assertTrue(u.is_no_unit()) + assert u.is_no_unit() def test_no_unit_representations(self): representations = ["no_unit", "no unit", "no-unit", "nounit"] @@ -779,53 +783,53 @@ def test_no_unit_representations(self): def test_unknown(self): u = Unit("unknown") - self.assertFalse(u.is_no_unit()) + assert not u.is_no_unit() def test_known_unit(self): u = Unit("meters") - self.assertFalse(u.is_no_unit()) + assert not u.is_no_unit() class Test_is_udunits(unittest.TestCase): def test_basic(self): u = Unit("meters") - self.assertTrue(u.is_udunits()) + assert u.is_udunits() def test_unknown(self): u = Unit("unknown") - self.assertFalse(u.is_udunits()) + assert not u.is_udunits() def test_no_unit(self): u = Unit("no_unit") - self.assertFalse(u.is_udunits()) + assert not u.is_udunits() class Test_is_time_reference(unittest.TestCase): def test_basic(self): u = Unit("hours since epoch") - self.assertTrue(u.is_time_reference()) + assert u.is_time_reference() def test_not_time_reference(self): u = Unit("hours") - self.assertFalse(u.is_time_reference()) + assert not u.is_time_reference() def test_unknown(self): u = Unit("unknown") - self.assertFalse(u.is_time_reference()) + assert not u.is_time_reference() def test_no_unit(self): u = Unit("no_unit") - self.assertFalse(u.is_time_reference()) + assert not u.is_time_reference() class Test_title(unittest.TestCase): def test_basic(self): u = Unit("meter") - self.assertEqual(u.title(10), "10 meter") + assert u.title(10) == "10 meter" def test_time_unit(self): u = Unit("hours since epoch", calendar=unit.CALENDAR_STANDARD) - self.assertEqual(u.title(10), "1970-01-01 10:00:00") + assert u.title(10) == "1970-01-01 10:00:00" class Test__immutable(unittest.TestCase): @@ -837,7 +841,7 @@ def test_immutable(self): u = Unit("m") for name in dir(u): emsg = "Instances .* are immutable" - with self.assertRaisesRegex(AttributeError, emsg): + with pytest.raises(AttributeError, match=emsg): self._set_attr(u, name) def test_common_hash(self): @@ -848,14 +852,14 @@ def test_common_hash(self): h = set() for u in (u1, u2, u3): h.add(hash(u)) - self.assertEqual(len(h), 1) + assert len(h) == 1 # Test different instances of electrical units (V) have a common hash. v1 = Unit("V") v2 = Unit("volt") for u in (v1, v2): h.add(hash(u)) - self.assertEqual(len(h), 2) + assert len(h) == 2 class Test__inplace(unittest.TestCase): @@ -872,14 +876,14 @@ def test(self): converted = c.convert(orig, f) emsg = "Arrays are not equal" - with self.assertRaisesRegex(AssertionError, emsg): + with pytest.raises(AssertionError, match=emsg): np.testing.assert_array_equal(orig, converted) - self.assertFalse(np.may_share_memory(orig, converted)) + assert not np.may_share_memory(orig, converted) # Test inplace conversion alters the original array. converted = c.convert(orig, f, inplace=True) np.testing.assert_array_equal(orig, converted) - self.assertTrue(np.may_share_memory(orig, converted)) + assert np.may_share_memory(orig, converted) def test_multidim_masked(self): c = Unit("deg_c") @@ -898,14 +902,14 @@ def test_multidim_masked(self): converted = c.convert(orig, f) emsg = "Arrays are not equal" - with self.assertRaisesRegex(AssertionError, emsg): + with pytest.raises(AssertionError, match=emsg): np.testing.assert_array_equal(orig.data, converted.data) - self.assertFalse(np.may_share_memory(orig, converted)) + assert not np.may_share_memory(orig, converted) # Test inplace conversion alters the original array. converted = c.convert(orig, f, inplace=True) np.testing.assert_array_equal(orig.data, converted.data) - self.assertTrue(np.may_share_memory(orig, converted)) + assert np.may_share_memory(orig, converted) def test_foreign_endian(self): c = Unit("deg_c") @@ -918,7 +922,7 @@ def test_foreign_endian(self): "Unable to convert non-native byte ordered array in-place. " "Consider byte-swapping first." ) - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): c.convert(orig, f, inplace=True) # Test we can do this when not-inplace @@ -928,22 +932,20 @@ def test_foreign_endian(self): class TestTimeEncoding(unittest.TestCase): def test_encode_time(self): result = unit.encode_time(2006, 1, 15, 12, 6, 0) - self.assertEqual(result, 159019560.0) + assert result == 159019560.0 def test_encode_date(self): result = unit.encode_date(2006, 1, 15) - self.assertEqual(result, 158976000.0) + assert result == 158976000.0 def test_encode_clock(self): result = unit.encode_clock(12, 6, 0) - self.assertEqual(result, 43560.0) + assert result == 43560.0 def test_decode_time(self): result = unit.decode_time(158976000.0 + 43560.0) year, month, day, hour, min, sec, res = result - self.assertEqual( - (year, month, day, hour, min, sec), (2006, 1, 15, 12, 6, 0) - ) + assert (year, month, day, hour, min, sec) == (2006, 1, 15, 12, 6, 0) class TestNumsAndDates(unittest.TestCase): @@ -952,24 +954,24 @@ def test_num2date(self): "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_GREGORIAN ) res = u.num2date(1) - self.assertEqual(str(res), "2010-11-02 13:00:00") - self.assertEqual(res.calendar, "standard") - self.assertIsInstance(res, cftime.datetime) + assert str(res) == "2010-11-02 13:00:00" + assert res.calendar == "standard" + assert isinstance(res, cftime.datetime) def test_num2date_py_datetime_type(self): u = Unit( "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_STANDARD ) res = u.num2date(1, only_use_cftime_datetimes=False) - self.assertEqual(str(res), "2010-11-02 13:00:00") - self.assertIsInstance(res, datetime.datetime) + assert str(res) == "2010-11-02 13:00:00" + assert isinstance(res, datetime.datetime) def test_num2date_wrong_calendar(self): u = Unit( "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_360_DAY ) - with self.assertRaisesRegex( - ValueError, "illegal calendar or reference date" + with pytest.raises( + ValueError, match="illegal calendar or reference date" ): u.num2date( 1, @@ -982,7 +984,7 @@ def test_date2num(self): "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_STANDARD ) d = datetime.datetime(2010, 11, 2, 13, 0, 0) - self.assertEqual(str(u.num2date(u.date2num(d))), "2010-11-02 13:00:00") + assert str(u.num2date(u.date2num(d))) == "2010-11-02 13:00:00" def test_num2pydate_simple(self): u = Unit( @@ -990,15 +992,15 @@ def test_num2pydate_simple(self): ) result = u.num2pydate(1) expected = datetime.datetime(2010, 11, 2, 13) - self.assertEqual(result, expected) - self.assertIsInstance(result, datetime.datetime) + assert result == expected + assert isinstance(result, datetime.datetime) def test_num2pydate_wrong_calendar(self): u = Unit( "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_360_DAY ) - with self.assertRaisesRegex( - ValueError, "illegal calendar or reference date" + with pytest.raises( + ValueError, match="illegal calendar or reference date" ): u.num2pydate(1) @@ -1007,71 +1009,71 @@ class Test_as_unit(unittest.TestCase): def test_already_unit(self): u = Unit("m") result = unit.as_unit(u) - self.assertIs(result, u) + assert result is u def test_known_unit_str(self): u_str = "m" expected = Unit("m") result = unit.as_unit(u_str) - self.assertEqual(expected, result) + assert expected == result def test_not_unit_str(self): u_str = "wibble" emsg = "Failed to parse unit" - with self.assertRaisesRegex(ValueError, emsg): + with pytest.raises(ValueError, match=emsg): unit.as_unit(u_str) def test_unknown_str(self): u_str = "unknown" expected = Unit("unknown") result = unit.as_unit(u_str) - self.assertEqual(expected, result) + assert expected == result def test_no_unit_str(self): u_str = "no_unit" expected = Unit("no_unit") result = unit.as_unit(u_str) - self.assertEqual(expected, result) + assert expected == result class Test_is_time(unittest.TestCase): def test_basic(self): u = Unit("hours") - self.assertTrue(u.is_time()) + assert u.is_time() def test_not_time_unit(self): u = Unit("meters") - self.assertFalse(u.is_time()) + assert not u.is_time() def test_unknown(self): u = Unit("unknown") - self.assertFalse(u.is_time()) + assert not u.is_time() def test_no_unit(self): u = Unit("no_unit") - self.assertFalse(u.is_time()) + assert not u.is_time() class Test_is_vertical(unittest.TestCase): def test_pressure_unit(self): u = Unit("millibar") - self.assertTrue(u.is_vertical()) + assert u.is_vertical() def test_length_unit(self): u = Unit("meters") - self.assertTrue(u.is_vertical()) + assert u.is_vertical() def test_not_vertical_unit(self): u = Unit("hours") - self.assertFalse(u.is_vertical()) + assert not u.is_vertical() def test_unknown(self): u = Unit("unknown") - self.assertFalse(u.is_vertical()) + assert not u.is_vertical() def test_no_unit(self): u = Unit("no_unit") - self.assertFalse(u.is_vertical()) + assert not u.is_vertical() if __name__ == "__main__": diff --git a/cf_units/tests/unit/test__discard_microsecond.py b/cf_units/tests/unit/test__discard_microsecond.py index 3ed578fd..643fae80 100644 --- a/cf_units/tests/unit/test__discard_microsecond.py +++ b/cf_units/tests/unit/test__discard_microsecond.py @@ -23,7 +23,7 @@ def setUp(self): def test_single(self): dt = datetime.datetime(**self.kwargs, microsecond=7) actual = discard_microsecond(dt) - self.assertEqual(self.expected, actual) + assert self.expected == actual def test_multi(self): shape = (5, 2) @@ -49,7 +49,7 @@ def test_single(self): expected = cftime.datetime( **self.kwargs, microsecond=0, calendar=calendar ) - self.assertEqual(expected, actual) + assert expected == actual def test_multi(self): shape = (2, 5) @@ -87,10 +87,10 @@ def setUp(self): ) def test_single__none(self): - self.assertIsNone(discard_microsecond(None)) + assert discard_microsecond(None) is None def test_single__false(self): - self.assertFalse(discard_microsecond(False)) + assert not discard_microsecond(False) def test_multi__falsy(self): falsy = np.array([None, False, 0]) @@ -110,12 +110,12 @@ def test_masked(self): ma.masked, ] ) - self.assertEqual(expected.shape, actual.shape) + assert expected.shape == actual.shape for i, masked in enumerate(mask): if masked: - self.assertIs(expected[i], actual[i]) + assert expected[i] is actual[i] else: - self.assertEqual(expected[i], actual[i]) + assert expected[i] == actual[i] if __name__ == "__main__": diff --git a/cf_units/tests/unit/test__udunits2.py b/cf_units/tests/unit/test__udunits2.py index a92896ed..56bcd7ec 100644 --- a/cf_units/tests/unit/test__udunits2.py +++ b/cf_units/tests/unit/test__udunits2.py @@ -13,6 +13,7 @@ import unittest import numpy as np +import pytest from cf_units import _udunits2 as _ud from cf_units.config import get_xml_path @@ -32,15 +33,15 @@ def test_read_xml(self): except _ud.UdunitsError: system = _ud.read_xml(get_xml_path()) - self.assertIsNotNone(system) + assert system is not None def test_read_xml_invalid_path(self): - with self.assertRaises(_ud.UdunitsError) as cm: + with pytest.raises(_ud.UdunitsError) as cm: _ud.read_xml(b"/not/a/path.xml") ex = cm.exception - self.assertEqual(ex.status_msg(), "UT_OPEN_ARG") - self.assertEqual(ex.errnum, errno.ENOENT) + assert ex.status_msg() == "UT_OPEN_ARG" + assert ex.errnum == errno.ENOENT class Test_system(unittest.TestCase): @@ -58,36 +59,36 @@ def setUp(self): def test_get_unit_by_name(self): unit = _ud.get_unit_by_name(self.system, b"metre") - self.assertIsNotNone(unit) + assert unit is not None def test_get_unit_by_name_invalid_unit(self): - with self.assertRaises(_ud.UdunitsError): + with pytest.raises(_ud.UdunitsError): _ud.get_unit_by_name(self.system, b"jigawatt") def test_parse(self): unit = _ud.parse(self.system, b"gigawatt", _ud.UT_ASCII) - self.assertIsNotNone(unit) + assert unit is not None def test_parse_latin1(self): angstrom = _ud.parse(self.system, b"\xe5ngstr\xF6m", _ud.UT_LATIN1) - self.assertIsNotNone(angstrom) + assert angstrom is not None def test_parse_ISO_8859_1(self): angstrom = _ud.parse(self.system, b"\xe5ngstr\xF6m", _ud.UT_ISO_8859_1) - self.assertIsNotNone(angstrom) + assert angstrom is not None def test_parse_UTF8(self): angstrom = _ud.parse( self.system, b"\xc3\xa5ngstr\xc3\xb6m", _ud.UT_UTF8 ) - self.assertIsNotNone(angstrom) + assert angstrom is not None def test_parse_invalid_unit(self): - with self.assertRaises(_ud.UdunitsError): + with pytest.raises(_ud.UdunitsError): _ud.parse(self.system, b"jigawatt", _ud.UT_ASCII) @@ -110,61 +111,61 @@ def setUp(self): def test_clone(self): metre_clone = _ud.clone(self.metre) - self.assertIsNot(metre_clone, self.metre) + assert metre_clone is not self.metre def test_is_dimensionless_true(self): radian = _ud.get_unit_by_name(self.system, b"radian") - self.assertTrue(_ud.is_dimensionless(radian)) + assert _ud.is_dimensionless(radian) def test_is_dimensionless_false(self): - self.assertFalse(_ud.is_dimensionless(self.metre)) + assert not _ud.is_dimensionless(self.metre) def test_compare_same_unit(self): - self.assertEqual(_ud.compare(self.metre, self.metre), 0) + assert _ud.compare(self.metre, self.metre) == 0 def test_compare_diff_unit(self): comp = _ud.compare(self.metre, self.second) comp_r = _ud.compare(self.second, self.metre) - self.assertNotEqual(comp, 0) - self.assertNotEqual(comp_r, 0) + assert comp != 0 + assert comp_r != 0 # m < s iff s > m - self.assertEqual(comp < 0, comp_r > 0) + assert (comp < 0) == (comp_r > 0) def test_are_convertible_true(self): - self.assertTrue(_ud.are_convertible(self.metre, self.yard)) + assert _ud.are_convertible(self.metre, self.yard) def test_are_convertible_false(self): - self.assertFalse(_ud.are_convertible(self.metre, self.second)) + assert not _ud.are_convertible(self.metre, self.second) def test_get_converter_valid(self): _ud.get_converter(self.metre, self.yard) def test_get_converter_invalid(self): - with self.assertRaises(_ud.UdunitsError) as cm: + with pytest.raises(_ud.UdunitsError) as cm: _ud.get_converter(self.metre, self.second) ex = cm.exception - self.assertEqual(ex.status_msg(), "UT_MEANINGLESS") + assert ex.status_msg() == "UT_MEANINGLESS" def test_scale(self): mm = _ud.scale(0.001, self.metre) - self.assertIsNotNone(mm) + assert mm is not None def test_offset(self): kelvin = _ud.get_unit_by_name(self.system, b"kelvin") celsius = _ud.offset(kelvin, 273.15) - self.assertIsNotNone(celsius) + assert celsius is not None def test_offset_by_time_valid(self): time_since = _ud.offset_by_time(self.second, -31622400.0) - self.assertIsNotNone(time_since) + assert time_since is not None def test_offset_by_time_invalid(self): - with self.assertRaises(_ud.UdunitsError) as cm: + with pytest.raises(_ud.UdunitsError) as cm: _ud.offset_by_time(self.metre, -31622400.0) cm.exception @@ -175,33 +176,33 @@ def test_offset_by_time_invalid(self): def test_multiply(self): metre_second = _ud.multiply(self.metre, self.second) - self.assertIsNotNone(metre_second) + assert metre_second is not None def test_invert(self): hertz = _ud.invert(self.second) - self.assertIsNotNone(hertz) + assert hertz is not None def test_divide(self): metres_per_second = _ud.divide(self.metre, self.second) - self.assertIsNotNone(metres_per_second) + assert metres_per_second is not None def test_raise_(self): sq_metre = _ud.raise_(self.metre, 2) - self.assertIsNotNone(sq_metre) + assert sq_metre is not None def test_root(self): hectare = _ud.get_unit_by_name(self.system, b"hectare") hundred_metre = _ud.root(hectare, 2) - self.assertIsNotNone(hundred_metre) + assert hundred_metre is not None def test_log(self): log_metre = _ud.log(2.7182818, self.metre) - self.assertIsNotNone(log_metre) + assert log_metre is not None def test_format(self): pascal = _ud.get_unit_by_name(self.system, b"pascal") @@ -210,10 +211,10 @@ def test_format(self): defn = _ud.format(pascal, _ud.UT_DEFINITION) name_defn = _ud.format(pascal, _ud.UT_DEFINITION | _ud.UT_NAMES) - self.assertEqual(symb, b"Pa") - self.assertEqual(name, b"pascal") - self.assertEqual(defn, b"m-1.kg.s-2") - self.assertEqual(name_defn, b"meter^-1-kilogram-second^-2") + assert symb == b"Pa" + assert name == b"pascal" + assert defn == b"m-1.kg.s-2" + assert name_defn == b"meter^-1-kilogram-second^-2" class Test_time_encoding(unittest.TestCase): @@ -226,14 +227,14 @@ def setUp(self): def test_encode_date(self): res_date_encoding = _ud.encode_date(self.year, self.month, self.day) - self.assertEqual(self.date_encoding, res_date_encoding) + assert self.date_encoding == res_date_encoding def test_encode_clock(self): res_clock_encoding = _ud.encode_clock( self.hours, self.minutes, self.seconds ) - self.assertEqual(self.clock_encoding, res_clock_encoding) + assert self.clock_encoding == res_clock_encoding def test_encode_time(self): res_time_encoding = _ud.encode_time( @@ -245,9 +246,7 @@ def test_encode_time(self): self.seconds, ) - self.assertEqual( - self.clock_encoding + self.date_encoding, res_time_encoding - ) + assert self.clock_encoding + self.date_encoding == res_time_encoding def test_decode_time(self): ( @@ -260,11 +259,14 @@ def test_decode_time(self): res_resolution, ) = _ud.decode_time(self.date_encoding + self.clock_encoding) - self.assertEqual( - (res_year, res_month, res_day, res_hours, res_minutes), - (self.year, self.month, self.day, self.hours, self.minutes), + assert (res_year, res_month, res_day, res_hours, res_minutes) == ( + self.year, + self.month, + self.day, + self.hours, + self.minutes, ) - self.assertTrue( + assert ( res_seconds - res_resolution < self.seconds < res_seconds + res_resolution diff --git a/cf_units/tests/unit/unit/test_Unit.py b/cf_units/tests/unit/unit/test_Unit.py index 9866d31d..d578e74f 100644 --- a/cf_units/tests/unit/unit/test_Unit.py +++ b/cf_units/tests/unit/unit/test_Unit.py @@ -8,6 +8,7 @@ import unittest import numpy as np +import pytest import cf_units from cf_units import Unit @@ -18,17 +19,17 @@ def test_capitalised_calendar(self): calendar = "StAnDaRd" expected = cf_units.CALENDAR_STANDARD u = Unit("hours since 1970-01-01 00:00:00", calendar=calendar) - self.assertEqual(u.calendar, expected) + assert u.calendar == expected def test_not_basestring_calendar(self): - with self.assertRaises(TypeError): + with pytest.raises(TypeError): Unit("hours since 1970-01-01 00:00:00", calendar=5) def test_hash_replacement(self): hash_unit = "m # s-1" expected = "m 1 s-1" u = Unit(hash_unit) - self.assertEqual(u, expected) + assert u == expected class Test_change_calendar(unittest.TestCase): @@ -38,7 +39,7 @@ def test_modern_standard_to_proleptic_gregorian(self): "hours since 1970-01-01 00:00:00", calendar="proleptic_gregorian" ) result = u.change_calendar("proleptic_gregorian") - self.assertEqual(result, expected) + assert result == expected def test_ancient_standard_to_proleptic_gregorian(self): u = Unit("hours since 1500-01-01 00:00:00", calendar="standard") @@ -46,33 +47,32 @@ def test_ancient_standard_to_proleptic_gregorian(self): "hours since 1500-01-10 00:00:00", calendar="proleptic_gregorian" ) result = u.change_calendar("proleptic_gregorian") - self.assertEqual(result, expected) + assert result == expected def test_no_change(self): u = Unit("hours since 1500-01-01 00:00:00", calendar="standard") result = u.change_calendar("standard") - self.assertEqual(result, u) + assert result == u # Docstring states that a new unit is returned, so check these are not # the same object. - self.assertIsNot(result, u) + assert result is not u def test_long_time_interval(self): u = Unit("months since 1970-01-01", calendar="standard") - with self.assertRaisesRegex(ValueError, "cannot be processed"): + with pytest.raises(ValueError, match="cannot be processed"): u.change_calendar("proleptic_gregorian") def test_wrong_calendar(self): u = Unit("days since 1900-01-01", calendar="360_day") - with self.assertRaisesRegex( - ValueError, "change_calendar only works for real-world calendars" + with pytest.raises( + ValueError, + match="change_calendar only works for real-world calendars", ): u.change_calendar("standard") def test_non_time_unit(self): u = Unit("m") - with self.assertRaisesRegex( - ValueError, "unit is not a time reference" - ): + with pytest.raises(ValueError, match="unit is not a time reference"): u.change_calendar("standard") @@ -86,7 +86,7 @@ def test_gregorian_calendar_conversion_setup(self): # causing an `is not` test to return a false negative. cal_str = cf_units.CALENDAR_GREGORIAN calendar = self.MyStr(cal_str) - self.assertIsNot(calendar, cal_str) + assert calendar is not cal_str u1 = Unit("hours since 1970-01-01 00:00:00", calendar=calendar) u2 = Unit("hours since 1969-11-30 00:00:00", calendar=calendar) u1point = np.array([8.0], dtype=np.float32) @@ -100,11 +100,11 @@ def test_gregorian_calendar_conversion_array(self): def test_gregorian_calendar_conversion_dtype(self): expected, result = self.test_gregorian_calendar_conversion_setup() - self.assertEqual(expected.dtype, result.dtype) + assert expected.dtype == result.dtype def test_gregorian_calendar_conversion_shape(self): expected, result = self.test_gregorian_calendar_conversion_setup() - self.assertEqual(expected.shape, result.shape) + assert expected.shape == result.shape def test_non_gregorian_calendar_conversion_dtype(self): for start_dtype, exp_convert in ( @@ -120,9 +120,9 @@ def test_non_gregorian_calendar_conversion_dtype(self): result = u1.convert(data, u2) if exp_convert: - self.assertEqual(result.dtype, start_dtype) + assert result.dtype == start_dtype else: - self.assertEqual(result.dtype, np.int64) + assert result.dtype == np.int64 class Test_convert__endianness_time(unittest.TestCase): @@ -229,12 +229,12 @@ def setUp(self): def test_default(self): # The dtype of a float array should be unchanged. result = self.deg.convert(self.degs_array, self.rad) - self.assertEqual(result.dtype, self.initial_dtype) + assert result.dtype == self.initial_dtype def test_integer_ctype_default(self): # The ctype of an int array should be cast to the default ctype. result = self.deg.convert(self.degs_array.astype(np.int32), self.rad) - self.assertEqual(result.dtype, cf_units.FLOAT64) + assert result.dtype == cf_units.FLOAT64 def test_integer_ctype_specified(self): # The ctype of an int array should be cast to the specified ctype if @@ -243,7 +243,7 @@ def test_integer_ctype_specified(self): result = self.deg.convert( self.degs_array.astype(np.int32), self.rad, ctype=expected_dtype ) - self.assertEqual(result.dtype, expected_dtype) + assert result.dtype == expected_dtype class Test_convert__masked_array(unittest.TestCase): @@ -279,24 +279,24 @@ def test_short_time_interval(self): # A short time interval is a time interval from seconds to days. unit = Unit("seconds since epoch") result = unit.is_long_time_interval() - self.assertFalse(result) + assert not result def test_long_time_interval(self): # A long time interval is a time interval of months or years. unit = Unit("months since epoch") result = unit.is_long_time_interval() - self.assertTrue(result) + assert result def test_calendar(self): # Check that a different calendar does not affect the result. unit = Unit("months since epoch", calendar=cf_units.CALENDAR_360_DAY) result = unit.is_long_time_interval() - self.assertTrue(result) + assert result def test_not_time_unit(self): unit = Unit("K") result = unit.is_long_time_interval() - self.assertFalse(result) + assert not result class Test_format(unittest.TestCase): @@ -305,7 +305,7 @@ def test_invalid_ut_unit(self): # format should be a little more tolerant of a Unit that has not been # constructed correctly when using pytest. unit = Unit.__new__(Unit) - self.assertEqual(unit.format(), "unknown") + assert unit.format() == "unknown" if __name__ == "__main__": diff --git a/cf_units/tests/unit/unit/test_as_unit.py b/cf_units/tests/unit/unit/test_as_unit.py index 23b4a35e..62b83f8a 100644 --- a/cf_units/tests/unit/unit/test_as_unit.py +++ b/cf_units/tests/unit/unit/test_as_unit.py @@ -29,9 +29,7 @@ def _assert_unit_equal(self, unit1, unit2): # Custom equality assertion of units since equality of the Unit class # utilises as_unit. for attribute in ["origin", "calendar", "category"]: - self.assertEqual( - getattr(unit1, attribute), getattr(unit2, attribute) - ) + assert getattr(unit1, attribute) == getattr(unit2, attribute) def test_cf_unit(self): # Ensure that as_unit returns the same cf_unit.Unit object and @@ -41,7 +39,7 @@ def test_cf_unit(self): result = as_unit(unit) self._assert_unit_equal(result, target) - self.assertIs(result, unit) + assert result is unit def test_non_cf_unit_no_calendar(self): # On passing as_unit a cf_unit.Unit-like object (not a cf_unit.Unit @@ -50,8 +48,8 @@ def test_non_cf_unit_no_calendar(self): unit = StubUnit() result = as_unit(unit) - self.assertEqual(result.calendar, "standard") - self.assertIsInstance(result, Unit) + assert result.calendar == "standard" + assert isinstance(result, Unit) def test_non_cf_unit_with_calendar(self): # On passing as_unit a cf_unit.Unit-like object (not a cf_unit.Unit From 83e1359e7849824fb015a2d0138af3cc38e2608d Mon Sep 17 00:00:00 2001 From: Ruth Comer Date: Thu, 26 May 2022 11:21:40 +0100 Subject: [PATCH 2/8] ran pytestify --- .../test__num2date_to_nearest_second.py | 2 +- cf_units/tests/integration/test_date2num.py | 4 +- cf_units/tests/integration/test_num2date.py | 2 +- cf_units/tests/integration/test_num2pydate.py | 2 +- cf_units/tests/test_coding_standards.py | 6 +- cf_units/tests/test_unit.py | 78 +++++++++---------- .../tests/unit/test__discard_microsecond.py | 12 +-- cf_units/tests/unit/test__udunits2.py | 18 ++--- cf_units/tests/unit/unit/test_Unit.py | 30 +++---- cf_units/tests/unit/unit/test_as_unit.py | 2 +- 10 files changed, 79 insertions(+), 77 deletions(-) diff --git a/cf_units/tests/integration/test__num2date_to_nearest_second.py b/cf_units/tests/integration/test__num2date_to_nearest_second.py index ae60e679..8ce19e61 100644 --- a/cf_units/tests/integration/test__num2date_to_nearest_second.py +++ b/cf_units/tests/integration/test__num2date_to_nearest_second.py @@ -16,7 +16,7 @@ from cf_units import _num2date_to_nearest_second -class Test(unittest.TestCase): +class Test: def setup_units(self, calendar): self.useconds = cf_units.Unit("seconds since 1970-01-01", calendar) self.uminutes = cf_units.Unit("minutes since 1970-01-01", calendar) diff --git a/cf_units/tests/integration/test_date2num.py b/cf_units/tests/integration/test_date2num.py index 1763e285..687e8b4c 100644 --- a/cf_units/tests/integration/test_date2num.py +++ b/cf_units/tests/integration/test_date2num.py @@ -14,8 +14,8 @@ from cf_units import date2num -class Test(unittest.TestCase): - def setUp(self): +class Test: + def setup_method(self): self.unit = "seconds since 1970-01-01" self.calendar = "gregorian" diff --git a/cf_units/tests/integration/test_num2date.py b/cf_units/tests/integration/test_num2date.py index 1f2b7ace..58d83a15 100644 --- a/cf_units/tests/integration/test_num2date.py +++ b/cf_units/tests/integration/test_num2date.py @@ -12,7 +12,7 @@ from cf_units import num2date -class Test(unittest.TestCase): +class Test: def test_num2date_wrong_calendar(self): with pytest.raises( ValueError, match="illegal calendar or reference date" diff --git a/cf_units/tests/integration/test_num2pydate.py b/cf_units/tests/integration/test_num2pydate.py index 302e5418..6227c29f 100644 --- a/cf_units/tests/integration/test_num2pydate.py +++ b/cf_units/tests/integration/test_num2pydate.py @@ -13,7 +13,7 @@ from cf_units import num2pydate -class Test(unittest.TestCase): +class Test: def test_num2pydate_simple(self): result = num2pydate(1, "days since 1970-01-01", calendar="standard") expected = datetime.datetime(1970, 1, 2) diff --git a/cf_units/tests/test_coding_standards.py b/cf_units/tests/test_coding_standards.py index c9689c86..dbd7cf71 100644 --- a/cf_units/tests/test_coding_standards.py +++ b/cf_units/tests/test_coding_standards.py @@ -11,6 +11,8 @@ from fnmatch import fnmatch from glob import glob +import pytest + import cf_units LICENSE_TEMPLATE = """# Copyright cf-units contributors @@ -35,7 +37,7 @@ ] -class TestLicenseHeaders(unittest.TestCase): +class TestLicenseHeaders: @staticmethod def whatchanged_parse(whatchanged_output): """ @@ -105,7 +107,7 @@ def test_license_headers(self): last_change_by_fname = self.last_change_by_fname() except ValueError: # Caught the case where this is not a git repo. - return self.skipTest( + return pytest.skip( "cf_units installation did not look like a " "git repo." ) diff --git a/cf_units/tests/test_unit.py b/cf_units/tests/test_unit.py index 9d1c7794..150f05fd 100644 --- a/cf_units/tests/test_unit.py +++ b/cf_units/tests/test_unit.py @@ -25,7 +25,7 @@ Unit = unit.Unit -class Test_unit__creation(unittest.TestCase): +class Test_unit__creation: def test_is_valid_unit_string(self): unit_strs = [" meter", "meter ", " meter "] for unit_str in unit_strs: @@ -77,7 +77,7 @@ def test_unicode_invalid(self): Unit("ø") -class Test_modulus(unittest.TestCase): +class Test_modulus: def test_modulus__degrees(self): u = Unit("degrees") assert u.modulus == 360.0 @@ -91,7 +91,7 @@ def test_no_modulus(self): assert u.modulus is None -class Test_is_convertible(unittest.TestCase): +class Test_is_convertible: def test_convert_distance_to_force(self): u = Unit("meter") v = Unit("newton") @@ -121,7 +121,7 @@ def test_convert_unknown_to_no_unit(self): assert not v.is_convertible(u) -class Test_is_dimensionless(unittest.TestCase): +class Test_is_dimensionless: def test_dimensionless(self): u = Unit("1") assert u.is_dimensionless() @@ -139,7 +139,7 @@ def test_no_unit_dimensionless(self): assert not u.is_dimensionless() -class Test_format(unittest.TestCase): +class Test_format: def test_basic(self): u = Unit("watt") assert u.format() == "W" @@ -187,7 +187,7 @@ def test_format_latin1(self): assert u.format(unit.UT_LATIN1) == "m²" -class Test_name(unittest.TestCase): +class Test_name: def test_basic(self): u = Unit("newton") assert u.name == "newton" @@ -201,7 +201,7 @@ def test_no_unit(self): assert u.name == "no_unit" -class Test_symbol(unittest.TestCase): +class Test_symbol: def test_basic(self): u = Unit("joule") assert u.symbol == "J" @@ -215,7 +215,7 @@ def test_no_unit(self): assert u.symbol == unit._NO_UNIT_SYMBOL -class Test_definition(unittest.TestCase): +class Test_definition: def test_basic(self): u = Unit("joule") assert u.definition == "m2.kg.s-2" @@ -229,7 +229,7 @@ def test_no_unit(self): assert u.definition == unit._NO_UNIT_SYMBOL -class Test__apply_offset(unittest.TestCase): +class Test__apply_offset: def test_add_integer_offset(self): u = Unit("meter") assert u + 10 == "m @ 10" @@ -253,7 +253,7 @@ def test_no_unit(self): operator.add(u, 10) -class Test_offset_by_time(unittest.TestCase): +class Test_offset_by_time: def test_offset(self): u = Unit("hour") v = u.offset_by_time(unit.encode_time(2007, 1, 15, 12, 6, 0)) @@ -282,7 +282,7 @@ def test_no_unit(self): u.offset_by_time(unit.encode_time(1970, 1, 1, 0, 0, 0)) -class Test_invert(unittest.TestCase): +class Test_invert: def test_basic(self): u = Unit("newton") assert u.invert() == "m-1.kg-1.s2" @@ -302,8 +302,8 @@ def test_invert_no_unit(self): u.invert() -class Test_root(unittest.TestCase): - def setUp(self): +class Test_root: + def setup_method(self): unit.suppress_errors() def test_square_root(self): @@ -340,7 +340,7 @@ def test_no_unit(self): u.root(2) -class Test_log(unittest.TestCase): +class Test_log: def test_base_2(self): u = Unit("hPa") assert u.log(2) == "lb(re 100 Pa)" @@ -371,7 +371,7 @@ def test_no_unit(self): u.log(10) -class Test_multiply(unittest.TestCase): +class Test_multiply: def test_multiply_by_int(self): u = Unit("amp") assert (u * 10).format() == "10 A" @@ -411,7 +411,7 @@ def test_multiply_unknown_and_no_unit(self): operator.mul(v, u) -class Test_divide(unittest.TestCase): +class Test_divide: def test_divide_by_int(self): u = Unit("watts") assert (u / 10).format() == "0.1 W" @@ -451,7 +451,7 @@ def test_divide_unknown_and_no_unit(self): truediv(v, u) -class Test_power(unittest.TestCase): +class Test_power: def test_basic(self): u = Unit("m^2") assert u**0.5 == Unit("m") @@ -497,8 +497,8 @@ def test_unit_power(self): operator.pow(u, v) -class Test_power__unknown(unittest.TestCase): - def setUp(self): +class Test_power__unknown: + def setup_method(self): self.u = Unit("unknown") def test_integer_power(self): @@ -522,8 +522,8 @@ def test_unit_power(self): operator.pow(self.u, v) -class Test_power__no_unit(unittest.TestCase): - def setUp(self): +class Test_power__no_unit: + def setup_method(self): self.u = Unit("no unit") def test_integer_power(self): @@ -553,7 +553,7 @@ def test_unit_power(self): operator.pow(self.u, v) -class Test_copy(unittest.TestCase): +class Test_copy: def test_basic(self): u = Unit("joule") assert copy.copy(u) == u @@ -569,7 +569,7 @@ def test_no_unit(self): assert copy.copy(u).is_no_unit() -class Test_stringify(unittest.TestCase): +class Test_stringify: def test___str__(self): u = Unit("meter") assert str(u) == "meter" @@ -586,7 +586,7 @@ def test___repr___time_unit(self): assert repr(u) == exp -class Test_equality(unittest.TestCase): +class Test_equality: def test_basic(self): u = Unit("meter") assert u == "meter" @@ -627,7 +627,7 @@ def test_not_implemented(self): assert not (u == {}) -class Test_non_equality(unittest.TestCase): +class Test_non_equality: def test_basic(self): u = Unit("meter") assert not (u != "meter") @@ -658,7 +658,7 @@ def test_not_implemented(self): assert u != {} -class Test_convert(unittest.TestCase): +class Test_convert: def test_convert_float(self): u = Unit("meter") v = Unit("mile") @@ -737,7 +737,7 @@ def test_incompatible_time_units(self): u.convert(u1point, v) -class Test_order(unittest.TestCase): +class Test_order: def test(self): m = Unit("meter") u = Unit("unknown") @@ -746,7 +746,7 @@ def test(self): assert sorted(start) == [m, n, u] -class Test_is_unknown(unittest.TestCase): +class Test_is_unknown: def _check(self, unknown_str): u = Unit(unknown_str) assert u.is_unknown() @@ -771,7 +771,7 @@ def test_no_ut_pointer(self): assert Unit.__new__(Unit).is_unknown() -class Test_is_no_unit(unittest.TestCase): +class Test_is_no_unit: def _check(self, no_unit_str): u = Unit(no_unit_str) assert u.is_no_unit() @@ -790,7 +790,7 @@ def test_known_unit(self): assert not u.is_no_unit() -class Test_is_udunits(unittest.TestCase): +class Test_is_udunits: def test_basic(self): u = Unit("meters") assert u.is_udunits() @@ -804,7 +804,7 @@ def test_no_unit(self): assert not u.is_udunits() -class Test_is_time_reference(unittest.TestCase): +class Test_is_time_reference: def test_basic(self): u = Unit("hours since epoch") assert u.is_time_reference() @@ -822,7 +822,7 @@ def test_no_unit(self): assert not u.is_time_reference() -class Test_title(unittest.TestCase): +class Test_title: def test_basic(self): u = Unit("meter") assert u.title(10) == "10 meter" @@ -832,7 +832,7 @@ def test_time_unit(self): assert u.title(10) == "1970-01-01 10:00:00" -class Test__immutable(unittest.TestCase): +class Test__immutable: def _set_attr(self, unit, name): setattr(unit, name, -999) raise ValueError("'Unit' attribute {!r} is mutable!".format(name)) @@ -862,7 +862,7 @@ def test_common_hash(self): assert len(h) == 2 -class Test__inplace(unittest.TestCase): +class Test__inplace: # Test shared memory for conversion operations. def test(self): @@ -929,7 +929,7 @@ def test_foreign_endian(self): c.convert(orig, f) -class TestTimeEncoding(unittest.TestCase): +class TestTimeEncoding: def test_encode_time(self): result = unit.encode_time(2006, 1, 15, 12, 6, 0) assert result == 159019560.0 @@ -948,7 +948,7 @@ def test_decode_time(self): assert (year, month, day, hour, min, sec) == (2006, 1, 15, 12, 6, 0) -class TestNumsAndDates(unittest.TestCase): +class TestNumsAndDates: def test_num2date(self): u = Unit( "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_GREGORIAN @@ -1005,7 +1005,7 @@ def test_num2pydate_wrong_calendar(self): u.num2pydate(1) -class Test_as_unit(unittest.TestCase): +class Test_as_unit: def test_already_unit(self): u = Unit("m") result = unit.as_unit(u) @@ -1036,7 +1036,7 @@ def test_no_unit_str(self): assert expected == result -class Test_is_time(unittest.TestCase): +class Test_is_time: def test_basic(self): u = Unit("hours") assert u.is_time() @@ -1054,7 +1054,7 @@ def test_no_unit(self): assert not u.is_time() -class Test_is_vertical(unittest.TestCase): +class Test_is_vertical: def test_pressure_unit(self): u = Unit("millibar") assert u.is_vertical() diff --git a/cf_units/tests/unit/test__discard_microsecond.py b/cf_units/tests/unit/test__discard_microsecond.py index 643fae80..1e8b5e94 100644 --- a/cf_units/tests/unit/test__discard_microsecond.py +++ b/cf_units/tests/unit/test__discard_microsecond.py @@ -15,8 +15,8 @@ from cf_units import _discard_microsecond as discard_microsecond -class Test__datetime(unittest.TestCase): - def setUp(self): +class Test__datetime: + def setup_method(self): self.kwargs = dict(year=1, month=2, day=3, hour=4, minute=5, second=6) self.expected = datetime.datetime(**self.kwargs, microsecond=0) @@ -37,8 +37,8 @@ def test_multi(self): np.testing.assert_array_equal(expected, actual) -class Test__cftime(unittest.TestCase): - def setUp(self): +class Test__cftime: + def setup_method(self): self.kwargs = dict(year=1, month=2, day=3, hour=4, minute=5, second=6) self.calendars = cftime._cftime._calendars @@ -74,8 +74,8 @@ def test_multi(self): np.testing.assert_array_equal(expected, actual) -class Test__falsy(unittest.TestCase): - def setUp(self): +class Test__falsy: + def setup_method(self): self.kwargs = dict(year=1, month=2, day=3, hour=4, minute=5, second=6) self.calendar = "360_day" microsecond = 7 diff --git a/cf_units/tests/unit/test__udunits2.py b/cf_units/tests/unit/test__udunits2.py index 56bcd7ec..bb0ccb03 100644 --- a/cf_units/tests/unit/test__udunits2.py +++ b/cf_units/tests/unit/test__udunits2.py @@ -21,7 +21,7 @@ _ud.set_error_message_handler(_ud.ignore) -class Test_get_system(unittest.TestCase): +class Test_get_system: """ Test case for operations which create a system object. @@ -44,13 +44,13 @@ def test_read_xml_invalid_path(self): assert ex.errnum == errno.ENOENT -class Test_system(unittest.TestCase): +class Test_system: """ Test case for system operations. """ - def setUp(self): + def setup_method(self): try: self.system = _ud.read_xml() except _ud.UdunitsError: @@ -92,13 +92,13 @@ def test_parse_invalid_unit(self): _ud.parse(self.system, b"jigawatt", _ud.UT_ASCII) -class Test_unit(unittest.TestCase): +class Test_unit: """ Test case for unit operations. """ - def setUp(self): + def setup_method(self): try: self.system = _ud.read_xml() except _ud.UdunitsError: @@ -217,8 +217,8 @@ def test_format(self): assert name_defn == b"meter^-1-kilogram-second^-2" -class Test_time_encoding(unittest.TestCase): - def setUp(self): +class Test_time_encoding: + def setup_method(self): self.year, self.month, self.day = 2000, 1, 1 self.date_encoding = -31622400.0 self.hours, self.minutes, self.seconds = 12, 34, 56 @@ -273,13 +273,13 @@ def test_decode_time(self): ) -class Test_convert(unittest.TestCase): +class Test_convert: """ Test case for convert operations. """ - def setUp(self): + def setup_method(self): try: system = _ud.read_xml() except _ud.UdunitsError: diff --git a/cf_units/tests/unit/unit/test_Unit.py b/cf_units/tests/unit/unit/test_Unit.py index d578e74f..f8fc87e8 100644 --- a/cf_units/tests/unit/unit/test_Unit.py +++ b/cf_units/tests/unit/unit/test_Unit.py @@ -14,7 +14,7 @@ from cf_units import Unit -class Test___init__(unittest.TestCase): +class Test___init__: def test_capitalised_calendar(self): calendar = "StAnDaRd" expected = cf_units.CALENDAR_STANDARD @@ -32,7 +32,7 @@ def test_hash_replacement(self): assert u == expected -class Test_change_calendar(unittest.TestCase): +class Test_change_calendar: def test_modern_standard_to_proleptic_gregorian(self): u = Unit("hours since 1970-01-01 00:00:00", calendar="standard") expected = Unit( @@ -76,7 +76,7 @@ def test_non_time_unit(self): u.change_calendar("standard") -class Test_convert__calendar(unittest.TestCase): +class Test_convert__calendar: class MyStr(str): pass @@ -125,11 +125,11 @@ def test_non_gregorian_calendar_conversion_dtype(self): assert result.dtype == np.int64 -class Test_convert__endianness_time(unittest.TestCase): +class Test_convert__endianness_time: # Test the behaviour of converting time units of differing # dtype endianness. - def setUp(self): + def setup_method(self): self.time1_array = np.array([31.5, 32.5, 33.5]) self.time2_array = np.array([0.5, 1.5, 2.5]) self.time1_unit = cf_units.Unit( @@ -163,11 +163,11 @@ def test_big_endian(self): np.testing.assert_array_almost_equal(result, self.time2_array) -class Test_convert__endianness_deg_to_rad(unittest.TestCase): +class Test_convert__endianness_deg_to_rad: # Test the behaviour of converting radial units of differing # dtype endianness. - def setUp(self): + def setup_method(self): self.degs_array = np.array([356.7, 356.8, 356.9]) self.rads_array = np.array([6.22558944, 6.22733477, 6.2290801]) self.deg = cf_units.Unit("degrees") @@ -189,11 +189,11 @@ def test_big_endian(self): np.testing.assert_array_almost_equal(result, self.rads_array) -class Test_convert__endianness_degC_to_kelvin(unittest.TestCase): +class Test_convert__endianness_degC_to_kelvin: # Test the behaviour of converting temperature units of differing # dtype endianness. - def setUp(self): + def setup_method(self): self.k_array = np.array([356.7, 356.8, 356.9]) self.degc_array = np.array([83.55, 83.65, 83.75]) self.degc = cf_units.Unit("degC") @@ -215,10 +215,10 @@ def test_big_endian(self): np.testing.assert_array_almost_equal(result, self.k_array) -class Test_convert__result_ctype(unittest.TestCase): +class Test_convert__result_ctype: # Test the output ctype of converting an cf_unit. - def setUp(self): + def setup_method(self): self.initial_dtype = np.float32 self.degs_array = np.array( [356.7, 356.8, 356.9], dtype=self.initial_dtype @@ -246,10 +246,10 @@ def test_integer_ctype_specified(self): assert result.dtype == expected_dtype -class Test_convert__masked_array(unittest.TestCase): +class Test_convert__masked_array: # Test converting an cf_unit with masked data. - def setUp(self): + def setup_method(self): self.deg = cf_units.Unit("degrees") self.rad = cf_units.Unit("radians") self.degs_array = np.ma.array( @@ -274,7 +274,7 @@ def test_type_conversion(self): np.testing.assert_array_almost_equal(self.rads_array, result) -class Test_is_long_time_interval(unittest.TestCase): +class Test_is_long_time_interval: def test_short_time_interval(self): # A short time interval is a time interval from seconds to days. unit = Unit("seconds since epoch") @@ -299,7 +299,7 @@ def test_not_time_unit(self): assert not result -class Test_format(unittest.TestCase): +class Test_format: def test_invalid_ut_unit(self): # https://github.com/SciTools/cf-units/issues/133 flagged up that # format should be a little more tolerant of a Unit that has not been diff --git a/cf_units/tests/unit/unit/test_as_unit.py b/cf_units/tests/unit/unit/test_as_unit.py index 62b83f8a..b979b121 100644 --- a/cf_units/tests/unit/unit/test_as_unit.py +++ b/cf_units/tests/unit/unit/test_as_unit.py @@ -24,7 +24,7 @@ def __str__(self): return self.origin -class TestAll(unittest.TestCase): +class TestAll: def _assert_unit_equal(self, unit1, unit2): # Custom equality assertion of units since equality of the Unit class # utilises as_unit. From bac8de2af196472651d2aa5227b0d44a9db9fbf3 Mon Sep 17 00:00:00 2001 From: Ruth Comer Date: Thu, 26 May 2022 11:27:38 +0100 Subject: [PATCH 3/8] remove unittest from py code --- .../tests/integration/test__num2date_to_nearest_second.py | 3 +-- cf_units/tests/integration/test_date2num.py | 3 +-- cf_units/tests/integration/test_num2date.py | 3 +-- cf_units/tests/integration/test_num2pydate.py | 3 +-- cf_units/tests/test_coding_standards.py | 3 +-- cf_units/tests/test_unit.py | 3 +-- cf_units/tests/unit/test__discard_microsecond.py | 4 ++-- cf_units/tests/unit/test__udunits2.py | 3 +-- cf_units/tests/unit/unit/test_Unit.py | 3 +-- cf_units/tests/unit/unit/test_as_unit.py | 5 +++-- 10 files changed, 13 insertions(+), 20 deletions(-) diff --git a/cf_units/tests/integration/test__num2date_to_nearest_second.py b/cf_units/tests/integration/test__num2date_to_nearest_second.py index 8ce19e61..99fadb24 100644 --- a/cf_units/tests/integration/test__num2date_to_nearest_second.py +++ b/cf_units/tests/integration/test__num2date_to_nearest_second.py @@ -6,7 +6,6 @@ """Test function :func:`cf_units._num2date_to_nearest_second`.""" import datetime -import unittest import cftime import numpy as np @@ -343,4 +342,4 @@ def test_fractional_second_365_day(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/integration/test_date2num.py b/cf_units/tests/integration/test_date2num.py index 687e8b4c..b83e2c8a 100644 --- a/cf_units/tests/integration/test_date2num.py +++ b/cf_units/tests/integration/test_date2num.py @@ -6,7 +6,6 @@ """Test function :func:`cf_units.date2num`.""" import datetime -import unittest import numpy as np import pytest @@ -73,4 +72,4 @@ def test_long_time_interval(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/integration/test_num2date.py b/cf_units/tests/integration/test_num2date.py index 58d83a15..6ff76059 100644 --- a/cf_units/tests/integration/test_num2date.py +++ b/cf_units/tests/integration/test_num2date.py @@ -5,7 +5,6 @@ # licensing details. """Test function :func:`cf_units.num2date`.""" -import unittest import pytest @@ -27,4 +26,4 @@ def test_num2date_wrong_calendar(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/integration/test_num2pydate.py b/cf_units/tests/integration/test_num2pydate.py index 6227c29f..81586abf 100644 --- a/cf_units/tests/integration/test_num2pydate.py +++ b/cf_units/tests/integration/test_num2pydate.py @@ -6,7 +6,6 @@ """Test function :func:`cf_units.num2pydate`.""" import datetime -import unittest import pytest @@ -28,4 +27,4 @@ def test_num2pydate_wrong_calendar(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/test_coding_standards.py b/cf_units/tests/test_coding_standards.py index dbd7cf71..e496b753 100644 --- a/cf_units/tests/test_coding_standards.py +++ b/cf_units/tests/test_coding_standards.py @@ -6,7 +6,6 @@ import os import subprocess -import unittest from datetime import datetime from fnmatch import fnmatch from glob import glob @@ -135,4 +134,4 @@ def test_license_headers(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/test_unit.py b/cf_units/tests/test_unit.py index 150f05fd..a54a647d 100644 --- a/cf_units/tests/test_unit.py +++ b/cf_units/tests/test_unit.py @@ -12,7 +12,6 @@ import datetime as datetime import operator import re -import unittest from operator import truediv import cftime @@ -1077,4 +1076,4 @@ def test_no_unit(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/unit/test__discard_microsecond.py b/cf_units/tests/unit/test__discard_microsecond.py index 1e8b5e94..b5a1305f 100644 --- a/cf_units/tests/unit/test__discard_microsecond.py +++ b/cf_units/tests/unit/test__discard_microsecond.py @@ -6,11 +6,11 @@ """Unit tests for the `cf_units._discard_microsecond` function.""" import datetime -import unittest import cftime import numpy as np import numpy.ma as ma +import pytest from cf_units import _discard_microsecond as discard_microsecond @@ -119,4 +119,4 @@ def test_masked(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/unit/test__udunits2.py b/cf_units/tests/unit/test__udunits2.py index bb0ccb03..c0d15534 100644 --- a/cf_units/tests/unit/test__udunits2.py +++ b/cf_units/tests/unit/test__udunits2.py @@ -10,7 +10,6 @@ exception where expected.""" import errno -import unittest import numpy as np import pytest @@ -312,4 +311,4 @@ def test_convert_doubles(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/unit/unit/test_Unit.py b/cf_units/tests/unit/unit/test_Unit.py index f8fc87e8..3ce8f239 100644 --- a/cf_units/tests/unit/unit/test_Unit.py +++ b/cf_units/tests/unit/unit/test_Unit.py @@ -5,7 +5,6 @@ # licensing details. """Unit tests for the `cf_units.Unit` class.""" -import unittest import numpy as np import pytest @@ -309,4 +308,4 @@ def test_invalid_ut_unit(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cf_units/tests/unit/unit/test_as_unit.py b/cf_units/tests/unit/unit/test_as_unit.py index b979b121..2092799e 100644 --- a/cf_units/tests/unit/unit/test_as_unit.py +++ b/cf_units/tests/unit/unit/test_as_unit.py @@ -6,7 +6,8 @@ """Unit tests for the `cf_units.as_unit` function.""" import copy -import unittest + +import pytest from cf_units import Unit, as_unit @@ -62,4 +63,4 @@ def test_non_cf_unit_with_calendar(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) From 96f0c786b110c75bcf960dbb5b27b30c116cfb3f Mon Sep 17 00:00:00 2001 From: Ruth Comer Date: Thu, 26 May 2022 12:09:18 +0100 Subject: [PATCH 4/8] fix udunits tests --- cf_units/tests/unit/test__udunits2.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/cf_units/tests/unit/test__udunits2.py b/cf_units/tests/unit/test__udunits2.py index c0d15534..1857b0ab 100644 --- a/cf_units/tests/unit/test__udunits2.py +++ b/cf_units/tests/unit/test__udunits2.py @@ -35,12 +35,11 @@ def test_read_xml(self): assert system is not None def test_read_xml_invalid_path(self): - with pytest.raises(_ud.UdunitsError) as cm: + with pytest.raises(_ud.UdunitsError) as ex: _ud.read_xml(b"/not/a/path.xml") - ex = cm.exception - assert ex.status_msg() == "UT_OPEN_ARG" - assert ex.errnum == errno.ENOENT + assert ex.match("UT_OPEN_ARG") + assert ex.value.errnum == errno.ENOENT class Test_system: @@ -141,11 +140,10 @@ def test_get_converter_valid(self): _ud.get_converter(self.metre, self.yard) def test_get_converter_invalid(self): - with pytest.raises(_ud.UdunitsError) as cm: + with pytest.raises(_ud.UdunitsError) as ex: _ud.get_converter(self.metre, self.second) - ex = cm.exception - assert ex.status_msg() == "UT_MEANINGLESS" + assert ex.match("UT_MEANINGLESS") def test_scale(self): mm = _ud.scale(0.001, self.metre) @@ -163,14 +161,15 @@ def test_offset_by_time_valid(self): assert time_since is not None + @pytest.mark.xfail def test_offset_by_time_invalid(self): - with pytest.raises(_ud.UdunitsError) as cm: + with pytest.raises(_ud.UdunitsError) as ex: _ud.offset_by_time(self.metre, -31622400.0) - cm.exception + + assert ex.match("UT_MEANINGLESS") # The udunits package should set a status of UT_MEANINGLESS, according # to the documentation. However, it is setting it to UT_SUCCESS. - # self.assertEqual(ex.status_msg(), 'UT_MEANINGLESS') def test_multiply(self): metre_second = _ud.multiply(self.metre, self.second) From b70487992c3770062dbf4c473be73e6eee6cee87 Mon Sep 17 00:00:00 2001 From: Ruth Comer Date: Thu, 26 May 2022 13:04:59 +0100 Subject: [PATCH 5/8] unit --> cf_units --- cf_units/tests/test_unit.py | 87 ++++++++++++++++++++----------------- 1 file changed, 48 insertions(+), 39 deletions(-) diff --git a/cf_units/tests/test_unit.py b/cf_units/tests/test_unit.py index a54a647d..1467af77 100644 --- a/cf_units/tests/test_unit.py +++ b/cf_units/tests/test_unit.py @@ -18,10 +18,10 @@ import numpy as np import pytest -import cf_units as unit +import cf_units from cf_units import suppress_errors -Unit = unit.Unit +Unit = cf_units.Unit class Test_unit__creation: @@ -36,25 +36,25 @@ def test_not_valid_unit_str(self): Unit("wibble") def test_calendar(self): - calendar = unit.CALENDAR_365_DAY + calendar = cf_units.CALENDAR_365_DAY u = Unit("hours since 1970-01-01 00:00:00", calendar=calendar) assert u.calendar == calendar def test_calendar_alias(self): - calendar = unit.CALENDAR_NO_LEAP + calendar = cf_units.CALENDAR_NO_LEAP u = Unit("hours since 1970-01-01 00:00:00", calendar=calendar) - assert u.calendar == unit.CALENDAR_365_DAY + assert u.calendar == cf_units.CALENDAR_365_DAY def test_no_calendar(self): u = Unit("hours since 1970-01-01 00:00:00") - assert u.calendar == unit.CALENDAR_STANDARD + assert u.calendar == cf_units.CALENDAR_STANDARD def test_unsupported_calendar(self): with pytest.raises(ValueError, match="unsupported calendar"): Unit("hours since 1970-01-01 00:00:00", calendar="wibble") def test_calendar_w_unicode(self): - calendar = unit.CALENDAR_365_DAY + calendar = cf_units.CALENDAR_365_DAY u = Unit("hours\xb2 hours-1 since epoch", calendar=calendar) assert u.calendar == calendar expected = "hours² hours-1 since 1970-01-01 00:00:00" @@ -145,27 +145,29 @@ def test_basic(self): def test_format_ascii(self): u = Unit("watt") - assert u.format(unit.UT_ASCII) == "W" + assert u.format(cf_units.UT_ASCII) == "W" def test_format_ut_names(self): u = Unit("watt") - assert u.format(unit.UT_NAMES) == "watt" + assert u.format(cf_units.UT_NAMES) == "watt" def test_format_unit_definition(self): u = Unit("watt") - assert u.format(unit.UT_DEFINITION) == "m2.kg.s-3" + assert u.format(cf_units.UT_DEFINITION) == "m2.kg.s-3" def test_format_multiple_options(self): u = Unit("watt") assert ( - u.format([unit.UT_NAMES, unit.UT_DEFINITION]) + u.format([cf_units.UT_NAMES, cf_units.UT_DEFINITION]) == "meter^2-kilogram-second^-3" ) def test_format_multiple_options_utf8(self): u = Unit("watt") assert ( - u.format([unit.UT_NAMES, unit.UT_DEFINITION, unit.UT_UTF8]) + u.format( + [cf_units.UT_NAMES, cf_units.UT_DEFINITION, cf_units.UT_UTF8] + ) == "meter²·kilogram·second⁻³" ) @@ -179,11 +181,11 @@ def test_format_no_unit(self): def test_format_names_utf8(self): u = Unit("m2") - assert u.format([unit.UT_UTF8, unit.UT_NAMES]) == "meter²" + assert u.format([cf_units.UT_UTF8, cf_units.UT_NAMES]) == "meter²" def test_format_latin1(self): u = Unit("m2") - assert u.format(unit.UT_LATIN1) == "m²" + assert u.format(cf_units.UT_LATIN1) == "m²" class Test_name: @@ -207,11 +209,11 @@ def test_basic(self): def test_unknown(self): u = Unit("unknown") - assert u.symbol == unit._UNKNOWN_UNIT_SYMBOL + assert u.symbol == cf_units._UNKNOWN_UNIT_SYMBOL def test_no_unit(self): u = Unit("no unit") - assert u.symbol == unit._NO_UNIT_SYMBOL + assert u.symbol == cf_units._NO_UNIT_SYMBOL class Test_definition: @@ -221,11 +223,11 @@ def test_basic(self): def test_unknown(self): u = Unit("unknown") - assert u.definition == unit._UNKNOWN_UNIT_SYMBOL + assert u.definition == cf_units._UNKNOWN_UNIT_SYMBOL def test_no_unit(self): u = Unit("no unit") - assert u.definition == unit._NO_UNIT_SYMBOL + assert u.definition == cf_units._NO_UNIT_SYMBOL class Test__apply_offset: @@ -255,7 +257,7 @@ def test_no_unit(self): class Test_offset_by_time: def test_offset(self): u = Unit("hour") - v = u.offset_by_time(unit.encode_time(2007, 1, 15, 12, 6, 0)) + v = u.offset_by_time(cf_units.encode_time(2007, 1, 15, 12, 6, 0)) assert v == "(3600 s) @ 20070115T120600.00000000 UTC" def test_not_numerical_offset(self): @@ -272,13 +274,13 @@ def test_unit_unknown(self): u = Unit("unknown") emsg = "Failed to offset" with pytest.raises(ValueError, match=emsg), suppress_errors(): - u.offset_by_time(unit.encode_time(1970, 1, 1, 0, 0, 0)) + u.offset_by_time(cf_units.encode_time(1970, 1, 1, 0, 0, 0)) def test_no_unit(self): u = Unit("no unit") emsg = "Failed to offset" with pytest.raises(ValueError, match=emsg), suppress_errors(): - u.offset_by_time(unit.encode_time(1970, 1, 1, 0, 0, 0)) + u.offset_by_time(cf_units.encode_time(1970, 1, 1, 0, 0, 0)) class Test_invert: @@ -303,7 +305,7 @@ def test_invert_no_unit(self): class Test_root: def setup_method(self): - unit.suppress_errors() + cf_units.suppress_errors() def test_square_root(self): u = Unit("volt^2") @@ -579,7 +581,8 @@ def test___repr___basic(self): def test___repr___time_unit(self): u = Unit( - "hours since 2007-01-15 12:06:00", calendar=unit.CALENDAR_GREGORIAN + "hours since 2007-01-15 12:06:00", + calendar=cf_units.CALENDAR_GREGORIAN, ) exp = "Unit('hours since 2007-01-15 12:06:00', calendar='standard')" assert repr(u) == exp @@ -827,7 +830,7 @@ def test_basic(self): assert u.title(10) == "10 meter" def test_time_unit(self): - u = Unit("hours since epoch", calendar=unit.CALENDAR_STANDARD) + u = Unit("hours since epoch", calendar=cf_units.CALENDAR_STANDARD) assert u.title(10) == "1970-01-01 10:00:00" @@ -930,19 +933,19 @@ def test_foreign_endian(self): class TestTimeEncoding: def test_encode_time(self): - result = unit.encode_time(2006, 1, 15, 12, 6, 0) + result = cf_units.encode_time(2006, 1, 15, 12, 6, 0) assert result == 159019560.0 def test_encode_date(self): - result = unit.encode_date(2006, 1, 15) + result = cf_units.encode_date(2006, 1, 15) assert result == 158976000.0 def test_encode_clock(self): - result = unit.encode_clock(12, 6, 0) + result = cf_units.encode_clock(12, 6, 0) assert result == 43560.0 def test_decode_time(self): - result = unit.decode_time(158976000.0 + 43560.0) + result = cf_units.decode_time(158976000.0 + 43560.0) year, month, day, hour, min, sec, res = result assert (year, month, day, hour, min, sec) == (2006, 1, 15, 12, 6, 0) @@ -950,7 +953,8 @@ def test_decode_time(self): class TestNumsAndDates: def test_num2date(self): u = Unit( - "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_GREGORIAN + "hours since 2010-11-02 12:00:00", + calendar=cf_units.CALENDAR_GREGORIAN, ) res = u.num2date(1) assert str(res) == "2010-11-02 13:00:00" @@ -959,7 +963,8 @@ def test_num2date(self): def test_num2date_py_datetime_type(self): u = Unit( - "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_STANDARD + "hours since 2010-11-02 12:00:00", + calendar=cf_units.CALENDAR_STANDARD, ) res = u.num2date(1, only_use_cftime_datetimes=False) assert str(res) == "2010-11-02 13:00:00" @@ -967,7 +972,8 @@ def test_num2date_py_datetime_type(self): def test_num2date_wrong_calendar(self): u = Unit( - "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_360_DAY + "hours since 2010-11-02 12:00:00", + calendar=cf_units.CALENDAR_360_DAY, ) with pytest.raises( ValueError, match="illegal calendar or reference date" @@ -980,14 +986,16 @@ def test_num2date_wrong_calendar(self): def test_date2num(self): u = Unit( - "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_STANDARD + "hours since 2010-11-02 12:00:00", + calendar=cf_units.CALENDAR_STANDARD, ) d = datetime.datetime(2010, 11, 2, 13, 0, 0) assert str(u.num2date(u.date2num(d))) == "2010-11-02 13:00:00" def test_num2pydate_simple(self): u = Unit( - "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_STANDARD + "hours since 2010-11-02 12:00:00", + calendar=cf_units.CALENDAR_STANDARD, ) result = u.num2pydate(1) expected = datetime.datetime(2010, 11, 2, 13) @@ -996,7 +1004,8 @@ def test_num2pydate_simple(self): def test_num2pydate_wrong_calendar(self): u = Unit( - "hours since 2010-11-02 12:00:00", calendar=unit.CALENDAR_360_DAY + "hours since 2010-11-02 12:00:00", + calendar=cf_units.CALENDAR_360_DAY, ) with pytest.raises( ValueError, match="illegal calendar or reference date" @@ -1007,31 +1016,31 @@ def test_num2pydate_wrong_calendar(self): class Test_as_unit: def test_already_unit(self): u = Unit("m") - result = unit.as_unit(u) + result = cf_units.as_unit(u) assert result is u def test_known_unit_str(self): u_str = "m" expected = Unit("m") - result = unit.as_unit(u_str) + result = cf_units.as_unit(u_str) assert expected == result def test_not_unit_str(self): u_str = "wibble" emsg = "Failed to parse unit" with pytest.raises(ValueError, match=emsg): - unit.as_unit(u_str) + cf_units.as_unit(u_str) def test_unknown_str(self): u_str = "unknown" expected = Unit("unknown") - result = unit.as_unit(u_str) + result = cf_units.as_unit(u_str) assert expected == result def test_no_unit_str(self): u_str = "no_unit" expected = Unit("no_unit") - result = unit.as_unit(u_str) + result = cf_units.as_unit(u_str) assert expected == result From d0bb08947dd6c919f796cde8ca89a1346fd0ea72 Mon Sep 17 00:00:00 2001 From: Ruth Comer Date: Thu, 26 May 2022 14:16:29 +0100 Subject: [PATCH 6/8] remove ifmains --- .../tests/integration/test__num2date_to_nearest_second.py | 4 ---- cf_units/tests/integration/test_date2num.py | 4 ---- cf_units/tests/integration/test_num2date.py | 4 ---- cf_units/tests/integration/test_num2pydate.py | 4 ---- cf_units/tests/test_coding_standards.py | 4 ---- cf_units/tests/test_unit.py | 4 ---- cf_units/tests/unit/test__discard_microsecond.py | 5 ----- cf_units/tests/unit/test__udunits2.py | 4 ---- cf_units/tests/unit/unit/test_Unit.py | 4 ---- cf_units/tests/unit/unit/test_as_unit.py | 6 ------ 10 files changed, 43 deletions(-) diff --git a/cf_units/tests/integration/test__num2date_to_nearest_second.py b/cf_units/tests/integration/test__num2date_to_nearest_second.py index 99fadb24..81f703ad 100644 --- a/cf_units/tests/integration/test__num2date_to_nearest_second.py +++ b/cf_units/tests/integration/test__num2date_to_nearest_second.py @@ -339,7 +339,3 @@ def test_fractional_second_365_day(self): ] # rounded up to this self.check_timedelta(nums, units, expected) - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/integration/test_date2num.py b/cf_units/tests/integration/test_date2num.py index b83e2c8a..7eb98b96 100644 --- a/cf_units/tests/integration/test_date2num.py +++ b/cf_units/tests/integration/test_date2num.py @@ -69,7 +69,3 @@ def test_long_time_interval(self): exp_emsg = 'interval of "months", "years" .* got "years".' with pytest.raises(ValueError, match=exp_emsg): date2num(date, unit, self.calendar) - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/integration/test_num2date.py b/cf_units/tests/integration/test_num2date.py index 6ff76059..dc85ddf0 100644 --- a/cf_units/tests/integration/test_num2date.py +++ b/cf_units/tests/integration/test_num2date.py @@ -23,7 +23,3 @@ def test_num2date_wrong_calendar(self): only_use_cftime_datetimes=False, only_use_python_datetimes=True, ) - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/integration/test_num2pydate.py b/cf_units/tests/integration/test_num2pydate.py index 81586abf..7c9ec603 100644 --- a/cf_units/tests/integration/test_num2pydate.py +++ b/cf_units/tests/integration/test_num2pydate.py @@ -24,7 +24,3 @@ def test_num2pydate_wrong_calendar(self): ValueError, match="illegal calendar or reference date" ): num2pydate(1, "days since 1970-01-01", calendar="360_day") - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/test_coding_standards.py b/cf_units/tests/test_coding_standards.py index e496b753..685833ba 100644 --- a/cf_units/tests/test_coding_standards.py +++ b/cf_units/tests/test_coding_standards.py @@ -131,7 +131,3 @@ def test_license_headers(self): raise AssertionError( "There were license header failures. See stdout." ) - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/test_unit.py b/cf_units/tests/test_unit.py index 1467af77..5bfc0fce 100644 --- a/cf_units/tests/test_unit.py +++ b/cf_units/tests/test_unit.py @@ -1082,7 +1082,3 @@ def test_unknown(self): def test_no_unit(self): u = Unit("no_unit") assert not u.is_vertical() - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/unit/test__discard_microsecond.py b/cf_units/tests/unit/test__discard_microsecond.py index b5a1305f..57dbd669 100644 --- a/cf_units/tests/unit/test__discard_microsecond.py +++ b/cf_units/tests/unit/test__discard_microsecond.py @@ -10,7 +10,6 @@ import cftime import numpy as np import numpy.ma as ma -import pytest from cf_units import _discard_microsecond as discard_microsecond @@ -116,7 +115,3 @@ def test_masked(self): assert expected[i] is actual[i] else: assert expected[i] == actual[i] - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/unit/test__udunits2.py b/cf_units/tests/unit/test__udunits2.py index 1857b0ab..e7dfe6e3 100644 --- a/cf_units/tests/unit/test__udunits2.py +++ b/cf_units/tests/unit/test__udunits2.py @@ -307,7 +307,3 @@ def test_convert_doubles(self): res = np.empty_like(arr) _ud.convert_doubles(self.converter, arr, res) np.testing.assert_array_almost_equal(arr * self.factor, res) - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/unit/unit/test_Unit.py b/cf_units/tests/unit/unit/test_Unit.py index 3ce8f239..b96e2abb 100644 --- a/cf_units/tests/unit/unit/test_Unit.py +++ b/cf_units/tests/unit/unit/test_Unit.py @@ -305,7 +305,3 @@ def test_invalid_ut_unit(self): # constructed correctly when using pytest. unit = Unit.__new__(Unit) assert unit.format() == "unknown" - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/cf_units/tests/unit/unit/test_as_unit.py b/cf_units/tests/unit/unit/test_as_unit.py index 2092799e..79661b3e 100644 --- a/cf_units/tests/unit/unit/test_as_unit.py +++ b/cf_units/tests/unit/unit/test_as_unit.py @@ -7,8 +7,6 @@ import copy -import pytest - from cf_units import Unit, as_unit @@ -60,7 +58,3 @@ def test_non_cf_unit_with_calendar(self): target = copy.copy(unit) result = as_unit(unit) self._assert_unit_equal(result, target) - - -if __name__ == "__main__": - pytest.main([__file__]) From 9f0fb082919712951739d7c83a186abda6127756 Mon Sep 17 00:00:00 2001 From: Ruth Comer Date: Thu, 26 May 2022 16:23:12 +0100 Subject: [PATCH 7/8] review actions --- cf_units/tests/integration/test_date2num.py | 13 ++++++------- cf_units/tests/unit/test__udunits2.py | 11 +++-------- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/cf_units/tests/integration/test_date2num.py b/cf_units/tests/integration/test_date2num.py index 7eb98b96..68e7c967 100644 --- a/cf_units/tests/integration/test_date2num.py +++ b/cf_units/tests/integration/test_date2num.py @@ -20,11 +20,10 @@ def setup_method(self): def test_single(self): date = datetime.datetime(1970, 1, 1, 0, 0, 5) - exp = 5.0 + exp = 5 res = date2num(date, self.unit, self.calendar) - # num2date won't return an exact value representing the date, - # even if one exists - assert round(abs(exp - res), 4) == 0 + + assert exp == res def test_sequence(self): dates = [ @@ -55,12 +54,12 @@ def test_multidim_sequence(self): res = date2num(dates, self.unit, self.calendar) assert exp_shape == res.shape - def test_discard_mircosecond(self): + def test_discard_microsecond(self): date = datetime.datetime(1970, 1, 1, 0, 0, 5, 750000) - exp = 5.0 + exp = 5 res = date2num(date, self.unit, self.calendar) - assert round(abs(exp - res), 4) == 0 + assert exp == res def test_long_time_interval(self): # This test should fail with an error that we need to catch properly. diff --git a/cf_units/tests/unit/test__udunits2.py b/cf_units/tests/unit/test__udunits2.py index e7dfe6e3..c939969a 100644 --- a/cf_units/tests/unit/test__udunits2.py +++ b/cf_units/tests/unit/test__udunits2.py @@ -35,10 +35,9 @@ def test_read_xml(self): assert system is not None def test_read_xml_invalid_path(self): - with pytest.raises(_ud.UdunitsError) as ex: + with pytest.raises(_ud.UdunitsError, match="UT_OPEN_ARG") as ex: _ud.read_xml(b"/not/a/path.xml") - assert ex.match("UT_OPEN_ARG") assert ex.value.errnum == errno.ENOENT @@ -140,11 +139,9 @@ def test_get_converter_valid(self): _ud.get_converter(self.metre, self.yard) def test_get_converter_invalid(self): - with pytest.raises(_ud.UdunitsError) as ex: + with pytest.raises(_ud.UdunitsError, match="UT_MEANINGLESS"): _ud.get_converter(self.metre, self.second) - assert ex.match("UT_MEANINGLESS") - def test_scale(self): mm = _ud.scale(0.001, self.metre) @@ -163,11 +160,9 @@ def test_offset_by_time_valid(self): @pytest.mark.xfail def test_offset_by_time_invalid(self): - with pytest.raises(_ud.UdunitsError) as ex: + with pytest.raises(_ud.UdunitsError, match="UT_MEANINGLESS"): _ud.offset_by_time(self.metre, -31622400.0) - assert ex.match("UT_MEANINGLESS") - # The udunits package should set a status of UT_MEANINGLESS, according # to the documentation. However, it is setting it to UT_SUCCESS. From aa00a5ce8169c07627b0970830edb61a4f736601 Mon Sep 17 00:00:00 2001 From: Ruth Comer Date: Thu, 26 May 2022 17:14:04 +0100 Subject: [PATCH 8/8] remove setup_method --- cf_units/tests/test_unit.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/cf_units/tests/test_unit.py b/cf_units/tests/test_unit.py index 5bfc0fce..f7379baa 100644 --- a/cf_units/tests/test_unit.py +++ b/cf_units/tests/test_unit.py @@ -304,9 +304,6 @@ def test_invert_no_unit(self): class Test_root: - def setup_method(self): - cf_units.suppress_errors() - def test_square_root(self): u = Unit("volt^2") assert u.root(2) == "V"