Skip to content

Commit e094104

Browse files
committed
Migrate message_data.testing.assert_units
1 parent 828cd22 commit e094104

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

message_ix_models/model/transport/testing.py

+25-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
from contextlib import nullcontext
55
from pathlib import Path
6-
from typing import Optional, Tuple
6+
from typing import TYPE_CHECKING, Mapping, Optional, Tuple, Union
77

88
import pytest
99
from genno import Computer
@@ -16,6 +16,10 @@
1616

1717
from . import Config, build
1818

19+
if TYPE_CHECKING:
20+
import pandas
21+
import pint
22+
1923
log = logging.getLogger(__name__)
2024

2125
# Common marks for transport code
@@ -34,6 +38,26 @@
3438
)
3539

3640

41+
def assert_units(
42+
df: "pandas.DataFrame", expected: Union[str, dict, "pint.Unit", "pint.Quantity"]
43+
):
44+
"""Assert that `df` has the unique, `expected` units."""
45+
import pint
46+
from iam_units import registry
47+
48+
all_units = df["unit"].unique()
49+
assert 1 == len(all_units), f"Non-unique {all_units = }"
50+
51+
# Convert the unique value to the same class as `expected`
52+
if isinstance(expected, pint.Quantity):
53+
assert expected == expected.__class__(1.0, all_units[0])
54+
elif isinstance(expected, Mapping):
55+
# Compare dimensionality of the units, rather than exact match
56+
assert expected == registry.Quantity(all_units[0] or "0").dimensionality
57+
else:
58+
assert expected == expected.__class__(all_units[0])
59+
60+
3761
def configure_build(
3862
test_context: Context,
3963
*,

0 commit comments

Comments
 (0)