From f5923b508ef0b1065d2ed2359a46c919988cd156 Mon Sep 17 00:00:00 2001 From: mscherer Date: Mon, 28 Oct 2024 16:26:39 +0100 Subject: [PATCH] test --- weldx_widgets/generic.py | 8 +++++++- weldx_widgets/tests/test_generic.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/weldx_widgets/generic.py b/weldx_widgets/generic.py index e3f4e9c..0b00ae6 100644 --- a/weldx_widgets/generic.py +++ b/weldx_widgets/generic.py @@ -134,7 +134,7 @@ def to_tree(self) -> dict: @staticmethod def convert_to_numpy_array(input_str): - if not WidgetTimeSeries.is_safe_nd_array(input_str): + if not is_safe_nd_array(input_str): raise RuntimeError(f"input_str '{input_str}' is not a safe array") a = np.array(ast.literal_eval(input_str)) return a @@ -159,6 +159,12 @@ def from_tree(self, tree: dict): self.base_data.text_value = repr(list(ts.data.magnitude)) self.base_unit.text_value = format(ts.data.units, "~") +def is_safe_nd_array(input_str : str): + """Check if input_string is a numerical array (allowing floats [with scientific notation), and ints.""" + # Regex pattern to match 1-D and N-D arrays with numbers + pattern = r'^\s*(\[\s*(?:(-?\d+(\.\d+)?([eE][+-]?\d+)?|\[\s*.*?\s*\])\s*(,\s*)?)*\]\s*|\s*(-?\d+(\.\d+)?([eE][+-]?\d+)?)(\s*,\s*(-?\d+(\.\d+)?([eE][+-]?\d+)?))*\s*)?\s*$' + + return bool(re.match(pattern, input_str)) def download_button( content: bytes, diff --git a/weldx_widgets/tests/test_generic.py b/weldx_widgets/tests/test_generic.py index b7b6cdf..7bd41bc 100644 --- a/weldx_widgets/tests/test_generic.py +++ b/weldx_widgets/tests/test_generic.py @@ -3,7 +3,9 @@ import pandas as pd import weldx + from weldx_widgets import WidgetTimeSeries +from weldx_widgets.generic import is_safe_nd_array def test_import_export(): @@ -19,3 +21,12 @@ def test_import_export(): ts2 = w.to_tree() assert ts2["timeseries"] == ts + + +def test_is_safe_nd_array(): + assert is_safe_nd_array("1, 2, 3") + assert is_safe_nd_array("[1, 2, 3]") + assert is_safe_nd_array("[[1, 2, 3], [4, 5, 6]]") + assert is_safe_nd_array("[[1.2e3, -4.5E-2], [3.4]]") + assert not is_safe_nd_array("[1, 2, 'evil']") + assert not is_safe_nd_array("1, 2, (x) => x")