Skip to content

Commit

Permalink
REFACTOR: General improvements (#5674)
Browse files Browse the repository at this point in the history
  • Loading branch information
SMoraisAnsys authored Jan 21, 2025
1 parent 5414fb3 commit 8c592a1
Show file tree
Hide file tree
Showing 7 changed files with 154 additions and 33 deletions.
4 changes: 2 additions & 2 deletions src/ansys/aedt/core/generic/data_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@

from decimal import Decimal
import math
import random
import re
import secrets
import string
import unicodedata

Expand Down Expand Up @@ -272,7 +272,7 @@ def random_string(length=6, only_digits=False, char_set=None):
char_set = string.digits
else:
char_set = string.ascii_uppercase + string.digits
random_str = "".join(random.choice(char_set) for _ in range(int(length)))
random_str = "".join(secrets.choice(char_set) for _ in range(int(length)))
return random_str


Expand Down
4 changes: 2 additions & 2 deletions src/ansys/aedt/core/modeler/cad/components_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
from __future__ import absolute_import

import os
import random
import re
import secrets
import warnings

from ansys.aedt.core.edb import Edb
Expand Down Expand Up @@ -172,7 +172,7 @@ def __init__(self, primitives, name=None, props=None, component_type=None):
"MaterialDefinitionParameters": {"VariableOrders": {}},
"MapInstanceParameters": "DesignVariable",
"UniqueDefinitionIdentifier": "89d26167-fb77-480e-a7ab-"
+ "".join(random.choice("abcdef0123456789") for _ in range(int(12))),
+ "".join(secrets.choice("abcdef0123456789") for _ in range(int(12))),
"OriginFilePath": "",
"IsLocal": False,
"ChecksumString": "",
Expand Down
39 changes: 14 additions & 25 deletions src/ansys/aedt/core/modeler/cad/modeler.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def _get_coordinates_data(self):
self._props = CsProps(self, props)
break
except Exception:
pass
self._modeler._app.logger.debug(f"Failed to get coordinate data using {ds}")

@pyaedt_function_handler()
def _dim_arg(self, value, units=None):
Expand Down Expand Up @@ -431,11 +431,8 @@ def __init__(self, modeler, props=None, name=None, face_id=None):
self._props = None
if props:
self._props = CsProps(self, props)
try: # pragma: no cover
if "KernelVersion" in self.props:
del self.props["KernelVersion"]
except Exception:
pass
if "KernelVersion" in self.props:
del self.props["KernelVersion"]

@property
def props(self):
Expand Down Expand Up @@ -703,11 +700,8 @@ def __init__(self, modeler, props=None, name=None):
self._props = None
if props:
self._props = CsProps(self, props)
try: # pragma: no cover
if "KernelVersion" in self.props:
del self.props["KernelVersion"]
except Exception:
pass
if "KernelVersion" in self.props:
del self.props["KernelVersion"]
self._ref_cs = None
self._quaternion = None
self._mode = None
Expand All @@ -717,15 +711,13 @@ def mode(self):
"""Coordinate System mode."""
if self._mode:
return self._mode
try:
if "Axis" in self.props["Mode"]:
self._mode = "axis"
elif "ZXZ" in self.props["Mode"]:
self._mode = "zxz"
elif "ZYZ" in self.props["Mode"]:
self._mode = "zyz"
except Exception:
pass
mode_parameter = self.props.get("Mode", "")
if "Axis" in mode_parameter:
self._mode = "axis"
if "ZXZ" in mode_parameter:
self._mode = "zxz"
elif "ZYZ" in mode_parameter:
self._mode = "zyz"
return self._mode

@mode.setter
Expand Down Expand Up @@ -1235,11 +1227,8 @@ def __init__(self, modeler, props=None, name=None, entity_id=None):
self._props = None
if props:
self._props = CsProps(self, props)
try: # pragma: no cover
if "KernelVersion" in self.props:
del self.props["KernelVersion"]
except Exception:
pass
if "KernelVersion" in self.props:
del self.props["KernelVersion"]
self._ref_cs = None

@property
Expand Down
4 changes: 3 additions & 1 deletion src/ansys/aedt/core/modeler/cad/object_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@

from ansys.aedt.core.generic.checks import min_aedt_version
from ansys.aedt.core.generic.constants import AEDT_UNITS
from ansys.aedt.core.generic.errors import AEDTRuntimeError
from ansys.aedt.core.generic.general_methods import _to_boolean
from ansys.aedt.core.generic.general_methods import _uname
from ansys.aedt.core.generic.general_methods import clamp
Expand Down Expand Up @@ -1758,7 +1759,8 @@ def clone(self):
"""
new_obj_tuple = self._primitives.clone(self.id)
success = new_obj_tuple[0]
assert success, f"Could not clone the object {self.name}."
if not success:
raise AEDTRuntimeError(f"Could not clone the object {self.name}")
new_name = new_obj_tuple[1][0]
return self._primitives[new_name]

Expand Down
10 changes: 7 additions & 3 deletions src/ansys/aedt/core/modeler/cad/polylines.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from ansys.aedt.core.application.variables import decompose_variable_value
from ansys.aedt.core.generic.constants import PLANE
from ansys.aedt.core.generic.constants import unit_converter
from ansys.aedt.core.generic.errors import AEDTRuntimeError
from ansys.aedt.core.generic.general_methods import _dim_arg
from ansys.aedt.core.generic.general_methods import pyaedt_function_handler
from ansys.aedt.core.modeler.cad.object_3d import Object3d
Expand Down Expand Up @@ -504,8 +505,10 @@ def _convert_points(p_in, dest_unit):
else:
nn_segments = None
nn_points = None
assert len(segments) == nn_segments, "Error getting the polyline segments from AEDT."
assert len(points) == nn_points, "Error getting the polyline points from AEDT."
if len(segments) != nn_segments:
raise AEDTRuntimeError("Failed to get the polyline segments from AEDT.")
if len(points) != nn_points:
raise AEDTRuntimeError("Failed to get the polyline points from AEDT.")
# if succeeded save the result
self._segment_types = segments
self._positions = points
Expand Down Expand Up @@ -740,7 +743,8 @@ def _segment_array(self, segment_data, start_index=0, start_point=None):

if segment_data.type == "AngularArc":
# from start-point and angle, calculate the mid- and end-points
assert start_point, "Start-point must be defined for an AngularArc Segment"
if not start_point:
raise ValueError("Start point must be defined for segment of type Angular Arc")
self._evaluate_arc_angle_extra_points(segment_data, start_point)

mod_units = self._primitives.model_units
Expand Down
50 changes: 50 additions & 0 deletions tests/unit/test_object_3d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 - 2025 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from unittest.mock import MagicMock
from unittest.mock import patch

from ansys.aedt.core.generic.errors import AEDTRuntimeError
from ansys.aedt.core.modeler.cad.object_3d import Object3d
import pytest


@pytest.fixture
def object_3d_setup():
"""Fixture used to mock the creation of a Object3d instance."""
with patch("ansys.aedt.core.modeler.cad.object_3d.Object3d.__init__", lambda x: None):
mock_instance = MagicMock(spec=Object3d)
yield mock_instance


def test_clone_failure(object_3d_setup):
mock_primitives = MagicMock()
mock_primitives.clone.return_value = [False]
object_3d = Object3d()
object_3d._primitives = mock_primitives
object_3d._m_name = "dummy"
object_3d._id = 12

with pytest.raises(AEDTRuntimeError, match="Could not clone the object dummy"):
object_3d.clone()
76 changes: 76 additions & 0 deletions tests/unit/test_polyline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 - 2025 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from unittest.mock import MagicMock
from unittest.mock import patch

from ansys.aedt.core.generic.errors import AEDTRuntimeError
from ansys.aedt.core.modeler.cad.polylines import Polyline
import pytest


@pytest.fixture
def polyline_setup():
"""Fixture used to mock the creation of a Polyline instance."""
with patch("ansys.aedt.core.modeler.cad.polylines.Polyline.__init__", lambda x: None):
mock_instance = MagicMock(spec=Polyline)
yield mock_instance


def test_segment_array_failure_for_segment_type_angular_arc(polyline_setup):
mock_segmenta_data = MagicMock()
mock_segmenta_data.num_points = 12
mock_segmenta_data.type = "AngularArc"
polyline = Polyline()

with pytest.raises(ValueError, match="Start point must be defined for segment of type Angular Arc"):
polyline._segment_array(mock_segmenta_data)


@patch("ansys.aedt.core.modeler.cad.polylines.Polyline.history")
def test_segment_update_segments_and_points_array_failure_on_segment(mock_history, polyline_setup):
properties = {"Number of curves": 42, "Number of points": 0}
custom_history = MagicMock()
custom_history.segments = None
custom_history.properties = properties
mock_history.return_value = custom_history
polyline = Polyline()
polyline.history = mock_history

with pytest.raises(AEDTRuntimeError, match="Failed to get the polyline segments from AEDT."):
polyline._update_segments_and_points()


@patch("ansys.aedt.core.modeler.cad.polylines.Polyline.history")
def test_segment_update_segments_and_points_array_failure_on_points(mock_history, polyline_setup):
properties = {"Number of curves": 0, "Number of points": 42}
custom_history = MagicMock()
custom_history.segments = None
custom_history.properties = properties
mock_history.return_value = custom_history
polyline = Polyline()
polyline.history = mock_history

with pytest.raises(AEDTRuntimeError, match="Failed to get the polyline points from AEDT."):
polyline._update_segments_and_points()

0 comments on commit 8c592a1

Please sign in to comment.