File size: 12,533 Bytes
a0ea4e3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | # Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import math
import random
import pytest
import isaaclab.utils.string as string_utils
from isaaclab.utils.string import _resolve_matching_names_impl
def test_resolvable_string_metadata_is_non_eager():
"""Test metadata access on ResolvableString without triggering import/resolve."""
ref = string_utils.ResolvableString("package.subpkg.module:Outer.InnerCallable")
assert ref.__module__ == "package.subpkg.module"
assert ref.__qualname__ == "Outer.InnerCallable"
assert ref.__name__ == "InnerCallable"
def test_resolvable_string_metadata_stable_after_resolution():
"""Test metadata before/after resolution remains consistent."""
ref = string_utils.ResolvableString("math:sin")
assert ref.__module__ == "math"
assert ref.__qualname__ == "sin"
assert ref.__name__ == "sin"
# Force resolution.
assert pytest.approx(ref(0.0), rel=0.0, abs=1e-9) == 0.0
# Metadata should remain identical after resolution cache is populated.
assert ref.__module__ == "math"
assert ref.__qualname__ == "sin"
assert ref.__name__ == "sin"
def test_resolvable_string_dunder_introspection_stays_lazy():
"""Test dunder probing doesn't force resolution for invalid references."""
ref = string_utils.ResolvableString("not_a_real_module.path:Nope")
# dunder attribute probe should not attempt import/resolve
assert hasattr(ref, "__dataclass_fields__") is False
# runtime use should still attempt resolve and fail
with pytest.raises(ValueError):
ref()
def test_resolvable_string_runtime_resolution_still_works():
"""Test runtime call path still resolves the callable target."""
ref = string_utils.ResolvableString("math:sin")
assert pytest.approx(ref(0.0), rel=0.0, abs=1e-9) == 0.0
def test_case_conversion():
"""Test case conversion between camel case and snake case."""
# test camel case to snake case
assert string_utils.to_snake_case("CamelCase") == "camel_case"
assert string_utils.to_snake_case("camelCase") == "camel_case"
assert string_utils.to_snake_case("CamelCaseString") == "camel_case_string"
# test snake case to camel case
assert string_utils.to_camel_case("snake_case", to="CC") == "SnakeCase"
assert string_utils.to_camel_case("snake_case_string", to="CC") == "SnakeCaseString"
assert string_utils.to_camel_case("snake_case_string", to="cC") == "snakeCaseString"
def test_string_to_callable_allows_safe_lambdas():
"""Test that simple lambda expressions and module references resolve to callables."""
assert string_utils.string_to_callable("lambda x: x + 1")(5) == 6
assert string_utils.string_to_callable("lambda x: x**2")(3) == 9
assert string_utils.string_to_callable("lambda x: x[0] if x else 0")([7, 8]) == 7
assert string_utils.string_to_callable("lambda x: x > 0 and x < 10")(5) is True
assert string_utils.string_to_callable("math:sqrt") is math.sqrt
@pytest.mark.parametrize(
"payload",
[
'lambda x: __import__("os").system("id")',
'lambda x: eval("1")',
"lambda x: (lambda: 1)()",
"lambda x: x.__class__",
"lambda x: __builtins__",
"lambda x: (y := 1)",
],
)
def test_string_to_callable_blocks_unsafe_lambdas(payload):
"""Test that lambda strings cannot execute code or traverse Python internals."""
with pytest.raises(ValueError, match="Unsafe lambda expression"):
string_utils.string_to_callable(payload)
def test_resolve_matching_names_with_basic_strings():
"""Test resolving matching names with a basic expression."""
# list of strings
target_names = ["a", "b", "c", "d", "e"]
# test matching names
query_names = ["a|c", "b"]
index_list, names_list = string_utils.resolve_matching_names(query_names, target_names)
assert index_list == [0, 1, 2]
assert names_list == ["a", "b", "c"]
# test matching names with regex
query_names = ["a.*", "b"]
index_list, names_list = string_utils.resolve_matching_names(query_names, target_names)
assert index_list == [0, 1]
assert names_list == ["a", "b"]
# test duplicate names
query_names = ["a|c", "b", "a|c"]
with pytest.raises(ValueError):
_ = string_utils.resolve_matching_names(query_names, target_names)
# test no regex match
query_names = ["a|c", "b", "f"]
with pytest.raises(ValueError):
_ = string_utils.resolve_matching_names(query_names, target_names)
def test_resolve_matching_names_with_joint_name_strings():
"""Test resolving matching names with joint names."""
# list of strings
robot_joint_names = []
for i in ["hip", "thigh", "calf"]:
for j in ["FL", "FR", "RL", "RR"]:
robot_joint_names.append(f"{j}_{i}_joint")
# test matching names
index_list, names_list = string_utils.resolve_matching_names(".*", robot_joint_names)
assert index_list == list(range(len(robot_joint_names)))
assert names_list == robot_joint_names
# test matching names with regex
index_list, names_list = string_utils.resolve_matching_names(".*_joint", robot_joint_names)
assert index_list == list(range(len(robot_joint_names)))
assert names_list == robot_joint_names
# test matching names with regex
index_list, names_list = string_utils.resolve_matching_names(["FL.*", "FR.*"], robot_joint_names)
ground_truth_index_list = [0, 1, 4, 5, 8, 9]
assert index_list == ground_truth_index_list
assert names_list == [robot_joint_names[i] for i in ground_truth_index_list]
# test matching names with regex
query_list = [
"FL_hip_joint",
"FL_thigh_joint",
"FR_hip_joint",
"FR_thigh_joint",
"FL_calf_joint",
"FR_calf_joint",
]
index_list, names_list = string_utils.resolve_matching_names(query_list, robot_joint_names)
ground_truth_index_list = [0, 1, 4, 5, 8, 9]
assert names_list != query_list
assert index_list == ground_truth_index_list
assert names_list == [robot_joint_names[i] for i in ground_truth_index_list]
# test matching names with regex but shuffled
# randomize order of previous query list
rng = random.Random(0)
rng.shuffle(query_list)
index_list, names_list = string_utils.resolve_matching_names(query_list, robot_joint_names)
ground_truth_index_list = [0, 1, 4, 5, 8, 9]
assert names_list != query_list
assert index_list == ground_truth_index_list
assert names_list == [robot_joint_names[i] for i in ground_truth_index_list]
def test_resolve_matching_names_with_preserved_order():
"""Test resolving matching names with preserved order."""
# list of strings and query list
robot_joint_names = []
for i in ["hip", "thigh", "calf"]:
for j in ["FL", "FR", "RL", "RR"]:
robot_joint_names.append(f"{j}_{i}_joint")
query_list = [
"FL_hip_joint",
"FL_thigh_joint",
"FR_hip_joint",
"FR_thigh_joint",
"FL_calf_joint",
"FR_calf_joint",
]
# test return in target ordering with sublist
query_list.reverse()
index_list, names_list = string_utils.resolve_matching_names(query_list, robot_joint_names, preserve_order=True)
ground_truth_index_list = [9, 8, 5, 1, 4, 0]
assert names_list == query_list
assert index_list == ground_truth_index_list
# test return in target ordering with regex expression
index_list, names_list = string_utils.resolve_matching_names(
["FR.*", "FL.*"], robot_joint_names, preserve_order=True
)
ground_truth_index_list = [1, 5, 9, 0, 4, 8]
assert index_list == ground_truth_index_list
assert names_list == [robot_joint_names[i] for i in ground_truth_index_list]
# test return in target ordering with a mix of regex and non-regex expression
index_list, names_list = string_utils.resolve_matching_names(
["FR.*", "FL_calf_joint", "FL_thigh_joint", "FL_hip_joint"], robot_joint_names, preserve_order=True
)
ground_truth_index_list = [1, 5, 9, 8, 4, 0]
assert index_list == ground_truth_index_list
assert names_list == [robot_joint_names[i] for i in ground_truth_index_list]
def test_resolve_matching_names_values_with_basic_strings():
"""Test resolving matching names with a basic expression."""
# list of strings
target_names = ["a", "b", "c", "d", "e"]
# test matching names
data = {"a|c": 1, "b": 2}
index_list, names_list, values_list = string_utils.resolve_matching_names_values(data, target_names)
assert index_list == [0, 1, 2]
assert names_list == ["a", "b", "c"]
assert values_list == [1, 2, 1]
# test matching names with regex
data = {"a|d|e": 1, "b|c": 2}
index_list, names_list, values_list = string_utils.resolve_matching_names_values(data, target_names)
assert index_list == [0, 1, 2, 3, 4]
assert names_list == ["a", "b", "c", "d", "e"]
assert values_list == [1, 2, 2, 1, 1]
# test matching names with regex
data = {"a|d|e|b": 1, "b|c": 2}
with pytest.raises(ValueError):
_ = string_utils.resolve_matching_names_values(data, target_names)
# test no regex match
query_names = {"a|c": 1, "b": 0, "f": 2}
with pytest.raises(ValueError):
_ = string_utils.resolve_matching_names_values(query_names, target_names)
def test_resolve_matching_names_values_with_strict_false():
"""Test resolving matching names with strict=False parameter."""
# list of strings
target_names = ["a", "b", "c", "d", "e"]
# test strict=False
data = {"a|c": 1, "b": 2, "f": 3}
index_list, names_list, values_list = string_utils.resolve_matching_names_values(data, target_names, strict=False)
assert index_list == [0, 1, 2]
assert names_list == ["a", "b", "c"]
assert values_list == [1, 2, 1]
# test failure case: multiple matches for a string (should still raise ValueError even with strict=False)
data = {"a|c": 1, "a": 2, "b": 3}
with pytest.raises(ValueError, match="Multiple matches for 'a':"):
_ = string_utils.resolve_matching_names_values(data, target_names, strict=False)
# test failure case: invalid input type (should still raise TypeError even with strict=False)
with pytest.raises(TypeError, match="Input argument `data` should be a dictionary"):
_ = string_utils.resolve_matching_names_values("not_a_dict", target_names, strict=False)
def test_resolve_matching_names_values_with_basic_strings_and_preserved_order():
"""Test resolving matching names with a basic expression."""
# list of strings
target_names = ["a", "b", "c", "d", "e"]
# test matching names
data = {"a|c": 1, "b": 2}
index_list, names_list, values_list = string_utils.resolve_matching_names_values(
data, target_names, preserve_order=True
)
assert index_list == [0, 2, 1]
assert names_list == ["a", "c", "b"]
assert values_list == [1, 1, 2]
# test matching names with regex
data = {"a|d|e": 1, "b|c": 2}
index_list, names_list, values_list = string_utils.resolve_matching_names_values(
data, target_names, preserve_order=True
)
assert index_list == [0, 3, 4, 1, 2]
assert names_list == ["a", "d", "e", "b", "c"]
assert values_list == [1, 1, 1, 2, 2]
# test matching names with regex
data = {"a|d|e|b": 1, "b|c": 2}
with pytest.raises(ValueError):
_ = string_utils.resolve_matching_names_values(data, target_names, preserve_order=True)
# test no regex match
query_names = {"a|c": 1, "b": 0, "f": 2}
with pytest.raises(ValueError):
_ = string_utils.resolve_matching_names_values(query_names, target_names, preserve_order=True)
def test_clear_resolve_matching_names_cache():
"""Clearing the cache discards previously cached entries."""
target_names = ["a", "b", "c"]
# Populate the cache
string_utils.resolve_matching_names("a", target_names)
info_before = _resolve_matching_names_impl.cache_info()
assert info_before.currsize > 0
# Clear the cache
string_utils.clear_resolve_matching_names_cache()
info_after = _resolve_matching_names_impl.cache_info()
assert info_after.currsize == 0
# Results are still correct after clearing
idx, names = string_utils.resolve_matching_names("a", target_names)
assert idx == [0]
assert names == ["a"]
|