Skip to content

Commit

Permalink
test
Browse files Browse the repository at this point in the history
  • Loading branch information
marscher committed Oct 28, 2024
1 parent aa70dae commit f5923b5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
8 changes: 7 additions & 1 deletion weldx_widgets/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down
11 changes: 11 additions & 0 deletions weldx_widgets/tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand All @@ -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")

0 comments on commit f5923b5

Please sign in to comment.